I am trying to implement the same stack overflow text-area with syntax highlighting in Python and have come this far but i am not able to get it working.
app.py
from flask import Flask, render_template, request
import preview
app = Flask(__name__)
#app.route('/',methods=['GET','POST'])
def index():
if request.method == 'POST':
markdown_content = request.args.get['wdd-input']
post_preview = preview.markdown(markdown_content['data'])
return render_template('test.html', result=post_preview)
if request.method == 'GET':
return render_template('demo.html')
if __name__ == '__main__':
app.run()
preview is something which does syntax highlighting and its based upon Pygments.
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PageDown Demo Page</title>
<link rel="stylesheet" type="text/css" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/static/css/highlighting.css">
<link rel="stylesheet" type="text/css" href="/static/css/demo.css" />
<script type="text/javascript" src="/static/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/static/js/hycus-textarea.js"></script>
<script type="text/javascript" src="/static/js/Markdown.Editor.js"></script>
<script type="text/javascript">
(function (m) {
m(document).ready(function () {
m('textarea.wmd-input').TextAreaResizer();
});
})(jQuery);
</script>
</head>
<body>
<div class="container">
<div id="pagedwon">
<div id="tabnav">
<ul class="nav nav-tabs" id="markdown_tab" style="padding: 0 10px; margin-bottom: 10px;">
<li class="active">Edit</li>
<li>Preview</li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane active" id="edit">
<div class="wmd-panel">
<div id="wmd-button-bar"></div>
<textarea class="wmd-input" id="wmd-input" rows="10" name="text-input">
This is the *pagedown* editor.
------------------------------
**Note**: Just plain **Markdown**, except that the input is sanitized: **HTML** is not allowed.
</textarea>
</div>
<script type="text/javascript">
(function () {
var pagedown_editor = new Markdown.Editor();
pagedown_editor.run();
})();
</script>
<script type="text/javascript">
(function (m) {
m("#markdown_tab a").click(function () {
if (m(this).html() == "Preview"){
var markdown_content = m("#wmd-input").val();
if (!markdown_content) {
m("div#markdownpreview").html("Empty Markdown Content.");
} else {
content_to_preview = {
"data": markdown_content
}
m.post("/", content_to_preview)
.success( function(preview_content){
if (preview_content == 'None'){
m("div#markdownpreview").html("No content received.");
} else {
m("div#markdownpreview").html(preview_content);
}
})
.error( function () {
m("div#markdownpreview").html("Sorry, error occurred. Please retry.");
});
}
}
});
})(jQuery);
</script>
</div>
<div class="tab-pane markdown-body" id="markdownpreview">
Loding preview content ...
</div>
</div>
</div>
</div>
</body>
</html>
This is log from the console:
127.0.0.1 - - [26/Jun/2014 20:25:01] "POST / HTTP/1.1" 500 -
How to get it working, please help. I am new to Flask.
First, request.args is for query string parameters, but you are sending over data via POST. You should be using request.form instead.
Second, MultiDict.get is a function, and does not support the __getitem__ protocol (which is the cause of your 500 error).
Third, as #Doobeh points out in the comments, you are sending the data over under the key data, but you are trying to access it via the key "wdd-input" - this will result in a BadRequest error.
Finally, the value extracted from request.form will be a string (which does not support strings as __getitem__ values) - and you don't need it anyway, as you already have the entire string.
A re-worked version of your POST portion:
if request.method == 'POST':
markdown_content = request.form.get('data', 'No content yet ...')
post_preview = preview.markdown(markdown_content)
return render_template('test.html', result=post_preview)
Related
What is the simplest way to change class name form .black to .white in the example below using python and flask framework? For example: after mouse click on div #area ?
CSS file:
#area {position:absolute;width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
HTML file:
<!doctype html>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static',filename='style.css')}}">
</head>
<body>
<div id="area" class="black"></div>
</body>
</html>
This need JavaScript and it has nothing to do with Flask
Example using querySelector()
<div id="area" class="black" onclick="change();"></div>
<script>
area = document.querySelector('#area');
function change(){
area.classList.replace('black', 'white');
}
</script>
or using special variable this
<div id="area" class="black" onclick="change(this);"></div>
<script>
function change(item){
item.classList.replace('black', 'white');
}
</script>
Eventually you could use addEventListener instead of onclick
<div id="area" class="black"></div>
<script>
function change(){
this.classList.replace('black', 'white');
}
area = document.querySelector('#area');
area.addEventListener('click', change);
</script>
or shorter
<div id="area" class="black"></div>
<script>
area = document.querySelector('#area');
area.addEventListener('click', function(){
this.classList.replace('black', 'white');
});
</script>
or even little shorter
<div id="area" class="black"></div>
<script>
document.querySelector('#area').addEventListener('click', function(){
this.classList.replace('black', 'white');
});
</script>
Minimal working code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<style>
#area1 {width:100px;height:100px;}
#area2 {width:100px;height:100px;}
#area3 {width:100px;height:100px;}
#area4 {width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
</style>
</head>
<body>
<div id="area1" class="black" onclick="change1();"></div>
<br>
<div id="area2" class="black" onclick="change2(this);"></div>
<br>
<div id="area3" class="black"></div>
<br>
<div id="area4" class="black"></div>
<script>
area1 = document.querySelector('#area1');
function change1(){
area1.classList.replace('black', 'white');
console.log('change1');
}
function change2(item){
item.classList.replace('black', 'white');
console.log('change2');
}
function change3(){
this.classList.replace('black', 'white');
console.log('change3');
}
area3 = document.querySelector('#area3');
area3.addEventListener('click', change3);
area4 = document.querySelector('#area4');
area4.addEventListener('click', function(){
this.classList.replace('black', 'white');
console.log('change4');
});
</script>
</body>
</html>
Using Python you would have to use <a></a> which would send information to server when you click it. And server would use Python to generate HTML with new class and send it back to browser. But it means to reload all page and it needs time.
Minimal working code:
I put black area in <a></a> which ?color=white and when server gets it then it sends back HTML with white area and with ?color=black, etc.
from flask import Flask, request, render_template_string
app = Flask(__name__)
#app.route('/')
def index():
color = request.args.get('color', 'black')
if color == 'black':
other = 'white'
else:
other = 'black'
return render_template_string('''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<style>
#area {width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
</style>
</head>
<body>
<div id="area" class="{{ color }}"></div>
</body>
</html>''', color=color, other=other)
if __name__ == '__main__':
app.run()
It is not popular but you can load JavaScript module Brython to run some Python code in web browser. But you can uses only modules converted to JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<style>
#area {width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.9.1/brython.min.js"></script>
</head>
<body onload="brython()">
<div id="area" class="black"></div>
<script type="text/python">
from browser import document
def change(ev):
if document['area'].attrs['class'] == 'black':
document['area'].attrs['class'] = 'white'
else:
document['area'].attrs['class'] = 'black'
document["area"].bind("click", change)
</script>
</body>
</html>
There is also transcrypt which can convert some Python code to JavaScript code and run in web browser.
Similar module RapydScript
Thanks, but it must be Python. I have found solution for printing a list, for example:
If I create a list called 'content'=['white','black'] the code below will print: white black and it works fine.
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static',filename='style.css')}}">
</head>
<body>
{% for x in content %}
{{x}}
{% endfor %}
</body>
</html>
So according to my question the code below should also work:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static',filename='style.css')}}">
</head>
<body>
{% if x==1 %}
<div id="area" class="white"></div>
{% else %}
<div id="area" class="black"></div>
{% endif %}
</body>
</html>
But it doesn't, any ideas?
I'm building a simple image navigator application in Python using Flask. I want to have forward and backward buttons to navigate through all the images in the static folder. So far, I've a single button which displays the image without refreshing the page. How can I navigate through the directory using buttons?
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('upload.html')
#app.route("/getimage")
def get_img():
return "00621.jpg"
if __name__ == '__main__':
app.run()
upload.html
<!DOCTYPE html>
<html lang="en">
<style>
img {
max-width: 100%;
max-height: 100%;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#retrieve').click(function(){
$.ajax({
url: "{{ url_for ('get_img') }}",
type : 'POST',
contentType: 'application/json;charset=UTF-8',
data : {'data':{{}}}
success: function(response) {
$("#myimg").attr('src', 'static/' + response);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Image Annotator</h1>
</div>
<button type='button' id ='retrieve'>Submit</button>
<img src="" id="myimg" />
</div>
</div>
</body>
</html>
I have reconstructed some of your code to achieve the answer. Please be aware that I've switched things from Jquery to JS.
New HTML Page:
<!DOCTYPE html>
<html lang="en">
<style>
img {
max-width: 100%;
max-height: 100%;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Image Annotator</h1>
</div>
<button type='button' onclick="oclick()" id='retrieve'>Submit</button>
<button onclick="action(2)" type="button">Backward</button><button onclick="action(1)" type="button">Forward</button>
<image src="" id="myimg"></image>
</div>
</div>
<script>
var imgap = 0
function oclick(){
var getInitialImage = new XMLHttpRequest();
getInitialImage.open("GET", "/getimage");
getInitialImage.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
document.getElementById("myimg").setAttribute("src", "/image/" + this.responseText);
}
}
getInitialImage.send();
}
function action(ac){
if (ac == 1){
imgap += 1
var getnextimagedetails = new XMLHttpRequest();
getnextimagedetails.open("GET", "/getimage?num=" + imgap.toString());
getnextimagedetails.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
document.getElementById("myimg").setAttribute("src", "/image/" + this.responseText);
}
}
getnextimagedetails.send();
}
if (ac == 2){
imgap += -1
var getlastimagedetails = new XMLHttpRequest();
getlastimagedetails.open("GET", "/getimage?num=" + imgap.toString());
getlastimagedetails.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
document.getElementById("myimg").setAttribute("src", "/image/" + this.responseText);
}
}
getlastimagedetails.send();
}
}
</script>
</body>
</html>
New Flask Document:
from flask import Flask, send_from_directory, request
import os
app = Flask(__name__)
#app.route("/")
def hello():
return send_from_directory('', 'upload.html')
#app.route("/image/<path:path>")
def image(path):
print(path)
if (path.endswith(".jpg") or path.endswith(".png") or path.endswith(".bmp") or path.endswith(".jpeg")):
return send_from_directory("", path)
return "", 500
#app.route("/getimage")
def get_img():
print(request.args.get("num"))
if (request.args.get("num") != None):
dirfiles = os.listdir()
presentedstr = []
for string in dirfiles:
if (string.endswith(".jpg") or string.endswith(".svg") or string.endswith(".bmp") or string.endswith(".jpeg") or string.endswith(".png")):
presentedstr.append(string)
presentedstr.index("00621.jpg")
return presentedstr[presentedstr.index("00621.jpg") + int(request.args.get("num"))]
else:
return "00621.jpg"
if __name__ == '__main__':
app.run()
How this implementation works, is the button will send out a request to the server for what the next image or item is, before making another request for the actual next image itself. It will search the same directory.
I am using starlette ASGI framework and want to render an HTML response.
Using a dummy route below to test passing a variable to javascript frontend.
#app.route('/error')
async def server_error(request):
template = 'analyze_response.html'
context = {"request": request}
return templates.TemplateResponse(template, context, data=75)
This is my 'analyze_response.html' file:
<html lang='en'>
<head>
<meta charset='utf-8'>
<link rel='stylesheet' href='../static/style.css'>
<script src='../static/client.js'></script>
<link rel="stylesheet" href="../static/cmGauge.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="../static/cmGauge.js"></script>
<script type="text/javascript">
var data = {{ data|tojson }}
</script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div>
<div class='center'>
<div class='title'>Sentiment Analysis of Movie Reviews</div>
<div class='content'>
<form action="/analyze" class="form" method="post">
<div class="form-group">
<textarea rows = "10" cols = "100" name = "review_text"></textarea><br>
</div>
<div class='analyze'>
<input type="submit" class="form-submit-button" value="Analyze">
</div>
</form>
<div id="gaugeDemo" class="gauge gauge-big gauge-green">
<div class="gauge-arrow" data-percentage="40"
style="transform: rotate(0deg);"></div>
</div>
<script type="text/javascript">
$('#gaugeDemo .gauge-arrow').cmGauge();
$('#gaugeDemo .gauge-arrow').trigger('updateGauge', myFunc());
</script>
</div>
</div>
</div>
</body>
As per some of the answers, I tried everything but it's still not working.
Getting below error:
File "app/server.py", line 125, in server_error
return templates.TemplateResponse(template, context, data=data) TypeError: TemplateResponse() got an unexpected keyword argument
'data'
Can you please let me know what the issue is? Thanks.
You need to pass it inside the context variable:
#app.route('/error')
async def server_error(request):
template = 'analyze_response.html'
context = {'request': request, 'data': 75}
return templates.TemplateResponse(template, context)
First, I am fairly new to javascript but I know my way around python. I am trying to learn javascript and I may be out of my league with trying this, but that is how you learn right.
Secondly, Flask and AngularJS play well together with a little help. Special thanks goes to shea256 (https://github.com/shea256/angular-flask)
Now, I am able to get the 'test application' up and running fairly easily.
However, I want to add DevExtreme to this stack and I am having some issues.
Here is what I have:
index.html
<!doctype html>
<html lang="en" ng-app="AngularFlask">
<head>
<meta charset="utf-8">
<title>AngularFlask</title>
<link rel="stylesheet" href="/static/css/bootstrap.css">
<link rel="stylesheet" href="/static/css/main.css">
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.common.css" />
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.light.css" />
<!--<script src="/static/lib/jquery/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <!--2.7.0-->
<!--<script src="/static/lib/angular/angular.js"></script>
<script src="/static/lib/angular/angular-resource.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-route.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-sanitize.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/globalize/0.1.1/globalize.min.js"></script>
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
-->
<script type="text/javascript" src="http://cdn3.devexpress.com/jslib/16.1.5/js/dx.web.js"></script>
<script src="/static/js/app.js"></script>
<script src="/static/js/controllers.js"></script>
<script src="/static/js/services.js"></script>
<script src="/static/lib/bootstrap/bootstrap.min.js"></script>
</head>
<body>
<div id="header" class="header navbar navbar-static-top">
<div class="navbar-inner">
<div class="container">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
</button>
<a class="brand" href="/">AngularFlask</a>
<div class="nav-collapse collapse">
<ul class="nav pull-right">
<li class="">
Home
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="container page">
<div id="content" class="container main" ng-view>
</div>
<hr>
<footer id="footer" class="footer">
<div class="footer-left">
About |
Home
</div>
<div class="footer-right">
<span>© 2013 AngularFlask</span>
</div>
</footer>
</div>
</body>
</html>
controllers.js
function IndexController($scope) {
}
function AboutController($scope) {
}
function PostListController($scope, Post) {
var postsQuery = Post.get({}, function(posts) {
$scope.posts = posts.objects;
});
}
function PostDetailController($scope, $routeParams, Post) {
var postQuery = Post.get({ postId: $routeParams.postId }, function(post) {
$scope.post = post;
});
}
app.js
'use strict';
angular.module('AngularFlask', ['angularFlaskServices', 'dx'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'static/partials/landing.html',
controller: IndexController
})
.when('/about', {
templateUrl: 'static/partials/about.html',
controller: AboutController
})
.when('/post', {
templateUrl: 'static/partials/post-list.html',
controller: PostListController
})
.when('/post/:postId', {
templateUrl: '/static/partials/post-detail.html',
controller: PostDetailController
})
/* Create a "/blog" route that takes the user to the same place as "/post" */
.when('/blog', {
templateUrl: 'static/partials/post-list.html',
controller: PostListController
})
.otherwise({
redirectTo: '/'
})
;
$locationProvider.html5Mode(true);
}])
;
With this, when I navigate to localhost:5000, this error is reported
https://docs.angularjs.org/error/$injector/modulerr?p0=AngularFlask&p1=%5B$injector:unpr%5D%20http:%2F%2Ferrors.angularjs.org%2F1.5.7%2F$injector%2Funpr%3Fp0%3D%2524routeProvider%0AO%2F%3C#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:6:412%0Adb%2Fn.$injector%3C#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:43:84%0Ad#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:40:344%0Ae#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:41:78%0Ah%2F%3C.invoke#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:41:163%0Ad#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:39:313%0Ag%2F%3C#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:39:445%0Ar#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:7:353%0Ag#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:39:222%0Adb#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:43:246%0ABc%2Fc#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:20:359%0ABc#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:21:163%0Age#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:19:484%0A#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:315:135%0An.Callbacks%2Fi#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:27444%0An.Callbacks%2Fj.fireWith#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:28213%0A.ready#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:30004%0AK#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:30366%0AO%2F%3C()%20angular.min.js:6g%2F%3C()%20angular.min.js:40r()%20angular.min.js:7g()%20angular.min.js:39db()%20angular.min.js:43Bc%2Fc()%20angular.min.js:20Bc()%20angular.min.js:21ge()%20angular.min.js:19%3Canonymous%3E%20angular.min.js:315n.Callbacks%2Fi()%20jquery.min.js:2n.Callbacks%2Fj.fireWith()%20jquery.min.js:2.ready()%20jquery.min.js:2K()%20jquery.min.js:21%20angular.min.js:6:412
It may be worth mentioning that if I use AngularJS 1.0.7 (included with Angular-Flask) the issue is cleared up until I add my html dev tag
<div dx-button="{
text: 'Generate random value'
}"></div>
then these are the errors:
Error: e.$$postDigest is not a function
Error: t.$root is undefined
Error: a.$watch is not a function
Error: c.$watch is not a function
Error: a.$watch is not a function
Error: t.dxTemplateModel is undefined
So this tells me that DevExpress is missing some functions in AngularJS 1.0.7; However, when using AngularJS 1.2.X Angular-Flask breaks. Is there anyway to get these two to play well together?
DevExtreme supports AngularJS 1.2 - 1.4. Your try to use too old version of AngularJS. Scripts in this repo were updated 3 years ago. But you can easily use another angularjs version. Your flask layout can look like below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }} - My Flask Application</title>
<link rel="stylesheet" type="text/css" href="/static/content/site.css" />
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.common.css" />
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.light.css" />
</head>
<body class="dx-theme-generic-typography" ng-app="myApp">
<div ng-controller="defaultCtrl">
<div dx-button="buttonOptions"></div>
</div>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular-sanitize.js"></script>
<script src="http://cdn3.devexpress.com/jslib/16.1.5/js/dx.all.js"></script>
<script src="/static/scripts/application.js"></script>
</body>
</html>
And the /static/scripts/application.js file:
var myApp = angular.module("myApp", ["dx"]);
myApp.controller("defaultCtrl", function($scope) {
$scope.buttonOptions = {
text: "My button",
onClick: function(){
alert("Hi!");
}
};
});
I have one phone number with a request url which works (speaks the text and then forwards the call) but then I have an app (a browser outbound call) going to the same request url and only the text to speech works, and the forwarding of the call gives an error and hangs up. Why doesn't it forward like the number's request url? I checked and the capability token renders fine...
views.py
def once_connected_view(request):
response = twiml.Response()
response.say("Please wait while we connect your call.", voice='alice')
response.dial("xxx-xx-xxx-xxxx")
return HttpResponse(str(response))
def home_view(request):
capability = TwilioCapability(account_sid, auth_token)
capability.allow_client_outgoing(application_sid)
token = capability.generate()
query_set = Model.objects.all()
return render(request, "base.html", {"query_set":query_set, "token":token})
urls.py
urlpatterns = [
url(r'^$', views.home_view, name="home"),
url(r'^once_connected/', views.once_connected_view, name="once_connected"),
]
number request url
http://xx.xx.com/once_connected/ http GET
app request url
http://xx.xx.com/once_connected/ http GET
main site url
https://xx.xx.com/
base.html
<!doctype html>
<head>
<script type="text/javascript" src="https://static.twilio.com/libs/twiliojs/1.2/twilio.min.js"></script>
<script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=320, height=device-height, target-densitydpi=medium-dpi" />
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'cars/responsive.css' %}">
</head>
<body>
<div class="container" id="wrapper">
<div class="video-background-container">
<video preload="auto" autoplay="" loop="" muted="" class="video-background hidden-xs hidden-sm">
<source type="video/mp4" src="omitted">
</video>
</div>
<div class="grid-overlay text-center">
<nav class="navbar navbar-default navbar-fixed-top" style="background:none;">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" id="logo" href="#">Brand Name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="replace-call">Contact Us</li>
</ul>
</div>
</div>
</nav>
...
<script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript">
/* Create the Client with a Capability Token */
Twilio.Device.setup("{{ token }}");
/* Let us know when the client is ready. */
Twilio.Device.ready(function (device) {
$(".replace-call").html("<a href='#' onclick='call()'>Call From Browser</a>");
});
/* Report any errors on the screen */
Twilio.Device.error(function (error) {
$(".replace-call").html('Contact Us');
});
Twilio.Device.connect(function (conn) {
$(".replace-call").html("<a href='#' onclick='hangup()'>End Call</a>");
});
/* Connect to Twilio when we call this function. */
function call() {
Twilio.Device.connect();
}
function hangup() {
Twilio.Device.disconnectAll();
$(".replace-call").html('Contact Us');
}
</script>
</body>
</html>
I am hosted on pythonanywhere.
After only minimal hair loss, I have made it work by adding a callerID attribute to the dial verb.
def once_connected_view(request):
response = twiml.Response()
response.say("Please wait while we connect your call.", voice='alice')
response.dial("xxx-xx-xxx-xxxx", callerId="+xxxxxxxxxx") # here
return HttpResponse(str(response))