from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
#app.route("/", methods=["POST", "GET"])
def index():
if request.method == "POST":
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
div#loading {
width: 50px;
height: 50px;
display: none;
background: url('https://i.giphy.com/3oEjI6SIIHBdRxXI40.gif') center no-repeat;
cursor: wait;
padding-left:100%;
}
</style>
</head>
<body>
<form method="POST">
<input type="text">
<button type="submit" onclick="loading();">
<div id="loading"></div>
<div id="content">
<i class="fas fa-search"></i>
</div>
</button>
</form>
<script type="text/javascript">
function loading(){
$("#loading").show();
$("#content").hide();
}
</script>
</body>
</html>
I'm building a Flask app, where when you press a button, a loader should replace the search glass icon with a loading gif.
At the moment, the gif isn't appearing upon clicking the button.
When I remove display:none from the loading style, the gif appears, so I know it's there.
You are using JQuery to show and hide the elements, but you have not included it in the template.
So include a script tag like
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
before the script tag where you're referencing JQuery
I figured I already had a div id = content and so it was removing the entire div. Remember to check your IDs!
Related
I want to have my page refresh itself after a successful download of a zip file since successive attempts to click the submit button result in an error, and the only way to remedy it fairly easily is to manually refresh/reload the page. I was wondering if there is a way to set it up so that once the zip is completed the page will refresh itself without the user having to worry about it. Doing it this way also kills two birds with one stone, since I want to disable the submit button to prevent users from spamming it, but if I end up having the page refresh I could just out right remove it after it's clicked.
Here is my HTML code:
{% load static %}
<html>
<head>
<link rel="stylesheet" href="{% static '/styleSheet.css' %}">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edstore">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--BOOTSTRAP ASSETS-->
<link href="https://fonts.googleapis.com/css2?family=Quicksand:wght#400;700&display=swap" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
<div class="main_Body">
<div class="section">
<h1>Fileconverter</h1>
<br>
<label for="file_field" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i>Updload File(s)</label>
<input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple>
<label id="file_name"></label>
<br>
<br><br><br>
<br>
<button type="submit" class="file-submit__button" onclick="formDisableButton()" id="submitButton">Testing</button> <!--onclick="formDisableButton"-->
</div>
</form>
</body>
<footer>
<p>Click "Choose File(s)" and select the files you want to convert.</p>
<p>Once you click "Submit" the job will start.</p>
<p>Upon completion, a zip folder will be downloaded in your browser.</p>
<p>Do not click the submit buttons multiple times. If the tab is loading, the job is being processed.</p>
</footer>
</html>
<script>
document.querySelector("#file_field").onchange = function(){
document.querySelector("#file_name").textContent = this.files[0].name;
}
const tempButton = document.getElementById("submitButton");
function formDisableButton(){
// tempButton.disabled = true;
// setTimeout(formEnableButton, 10000);
location.reload();
}
function formEnableButton(){
tempButton.disabled = false;
}
/*setTimeout(()=>{
btn.disabled = false;
console.log('Button Activated')
}, 10000)*/
/* $(function(){
$("#submitButton").click(function(){
$("#submitButton").attr("disabled", "disabled");
setTimeout(function(){
$("#submitButton").removeAttr("disabled");
}, 10000)
});
});*/
</script>
And here is the views.py file:
from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic.edit import FormView
from django.views.decorators.csrf import csrf_exempt
from .forms import FileFieldForm
from django.http import HttpResponse
from .perform_conversion import FileConverter
import zipfile
import io
def FileFieldFormView(request, *args, **kwargs):
form = FileFieldForm(request.POST)
files = request.FILES.getlist('file_field')
if request.method == 'POST':
form = FileFieldForm(request.POST, request.FILES)
if form.is_valid():
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", False) as zip_file:
for f in files:
fileconverter = FileConverter(f.name)
fileconverter.run(f.file)
for img_name, img in fileconverter.output.items():
data = io.BytesIO(img)
zip_file.writestr(img_name, data.getvalue())
# Set the return value of the HttpResponse
response = HttpResponse(zip_buffer.getvalue(), content_type='application/octet-stream')
# Set the HTTP header for sending to browser
response['Content-Disposition'] = "attachment; filename=%s" % 'zip.zip'
response.set_signed_cookie('csrftoken', request.COOKIES['csrftoken'])
# Return the response value
return response
else:
return HttpResponse('Form Invalid')
else:
return render(request, 'pages/file_converter.html')
Based on what I've seen after doing digging before asking this question, Ajax seems to be the right direction for things, but I have no experience with it and everything I find online doesn't seem to apply to the type of question I'm asking. Also the onclick for the submit button doesn't work, but that's not a main problem right now. TBH any help would be massively appreciated!
Use javascript onclick to change the button class from class="file-submit__button" to something like class="file-submit__button-disabled", and of course add the corresponding css.
I keep getting an error related to the csrf token when I try to employ consecutive submissions, and refreshing the page seems to work. The purpose of the program is to create zip files, so I figured the easiest solution would be to have the web page automatically reloaded once the zip file is done being created from the function in the views.py file and available for the user to open. The main issue I'm having is how to actually do that.
Here is the code for my HTML file:
{% load static %}
<html>
<head>
<link rel="stylesheet" href="{% static '/styleSheet.css' %}">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edstore">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--BOOTSTRAP ASSETS-->
<link href="https://fonts.googleapis.com/css2?family=Quicksand:wght#400;700&display=swap" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
<div class="main_Body">
<div class="section">
<h1>Fileconverter</h1>
<br>
<label for="file_field" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i>Updload File(s)</label>
<input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple>
<label id="file_name"></label>
<br>
<br><br><br>
<br>
<input type="submit" class="file-submit__button" id="submitButton"> <!--onclick="formDisableButton"-->
</div>
</form>
</body>
<footer>
<p>Click "Choose File(s)" and select the files you want to convert.</p>
<p>Once you click "Submit" the job will start.</p>
<p>Upon completion, a zip folder will be downloaded in your browser.</p>
<p>Do not click the submit buttons multiple times. If the tab is loading, the job is being processed.</p>
</footer>
</html>
<script>
document.querySelector("#file_field").onchange = function(){
document.querySelector("#file_name").textContent = this.files[0].name;
}
const tempButton = document.getElementById("submitButton");
function formDisableButton(){
tempButton.disabled = true;
setTimeout(formEnableButton, 10000);
}
function formEnableButton(){
tempButton.disabled = false;
}
/*setTimeout(()=>{
btn.disabled = false;
console.log('Button Activated')
}, 10000)*/
/* $(function(){
$("#submitButton").click(function(){
$("#submitButton").attr("disabled", "disabled");
setTimeout(function(){
$("#submitButton").removeAttr("disabled");
}, 10000)
});
});*/
And this is the code from my views.py file:
from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic.edit import FormView
from django.views.decorators.csrf import csrf_exempt
from .forms import FileFieldForm
from django.http import HttpResponse
from .perform_conversion import FileConverter
import zipfile
import io
def FileFieldFormView(request, *args, **kwargs):
form = FileFieldForm(request.POST)
files = request.FILES.getlist('file_field')
if request.method == 'POST':
print(request)
form = FileFieldForm(request.POST, request.FILES)
if form.is_valid():
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", False) as zip_file:
for f in files:
fileconverter = FileConverter(f.name)
fileconverter.run(f.file)
for img_name, img in fileconverter.output.items():
data = io.BytesIO(img)
zip_file.writestr(img_name, data.getvalue())
# Set the return value of the HttpResponse
response = HttpResponse(zip_buffer.getvalue(), content_type='application/octet-stream')
# Set the HTTP header for sending to browser
response['Content-Disposition'] = "attachment; filename=%s" % 'zip.zip'
response.set_signed_cookie('csrftoken', request.COOKIES['csrftoken'])
# Return the response value
return response
else:
return HttpResponse('Form Invalid')
else:
return render(request, 'file_converter.html')
As a bonus if you're willing to provide a bit of extra help, I can't ever seem to have any sort of onclick for my submission button. Every time I try to add it, the python files never actually end up running and the page just sits there. I'd like to have it so that when the submission button is clicked it is removed form the page to prevent excessive submission attempts and since, in theory, the page will be refreshing after a successful run through, the submit button will just be reposted onto the page.
I have a HTML control panel with various buttons and sliders. All of the buttons are operational and when clicked send a post request which my Python app receives and then executes functions.
I cannot seem to get the slider controls to work, When I adjust the slider I get the following error:
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'button'
This is promising as at least I can see it trying to do something and failing, which is the best result achieved thus far. My javascript and AJAX knowledge is limited and I need a solution for the slider to POST request on any onchange value that python can then interpret.
I initially had the following HTML:
<input id="slider" type="range" min="0" max="100" value="50" onchange="updateVolume(getElementById('slider').value); return false;">
Javascript:
<script>
function updateVolume (vol) {
$.ajax({
method: "POST",
url: '{{ url_for('main.control_panel', video_id=video.id) }}',
data: { volume: vol}
})
.done(function( msg ) {
// optional callback stuff if needed
// alert( "Data Saved: " + msg );
});
}
</script>
This threw up the same error.
This is my current code that also throws the same error:
HTML:
<input id="slide" type="range" min="1" max="100" step="1" value="10" name="slide">
<div id="sliderAmount"></div>
Javascript:
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
$.ajax({
url: '{{ url_for('main.control_panel', video_id=video.id) }}',
data: $('form').serialize(),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
}
Python:
#main.route("/control_panel/<int:video_id>", methods=['GET', 'POST'])
def control_panel(video_id):
video = video.query.get_or_404(video_id)
if request.method == 'POST':
... #IF ELIF for various button functions here
volume = request.form['slider']
return json.dumps({'volume': volume})
return render_template('/control_panel.html', title=video.video, video=video)
Any support would be greatly appreciated as I'm struggling to find solutions on the web along with me aforementioned js/ajax knowledge.
Thanks
EDIT:
This is a recreation of the problem:
python:
from flask import Flask, request, redirect, url_for, render_template, json
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def control_panel():
if request.method == 'POST':
if request.form['button'] == 'button-play':
print("play button pressed")
elif request.form['button'] == 'button-exit':
print("exit button pressed")
elif request.form['slider']:
volume = request.form['slider']
return json.dumps({'volume': volume})
print(volume)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
HTML:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Slider</title>
</head>
<body>
<div class="container" id="control_panel_1">
<form action="/" method ="post" enctype="multipart/form-data" id="form">
<div class="row">
<div class="col">
<button class="btn btn-primary" button type="submit" name="button" value="button-play">PLAY</button>
<button class="btn btn-primary" button type="submit" name="button" value="button-exit">EXIT</button>
<input id="slide" type="range" min="1" max="100" step="1" value="10" name="slide">
<div id="sliderAmount"></div>
</div>
</div>
</form>
<!--- SCRIPTS --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
<script>
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
$.ajax({
url: '/index.html',
data: $('form').serialize(),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
}
</script>
</html>
Problem is because $('form').serialize() sends only values from <input> but not from <button> but in Flask you check request.form['button'] and it raises error because key button doesn't exists in dictionary request.form.
You have to use
request.form.get('button')
and then it returns None when button doesn't exists in dictionary
BTW:
you have only #app.route("/", ...) so AJAX has to send to /, not to
/index.html
using print(volume) after return ... is useless becuse return ends function
in Flask you can use return jsonify(dict) instead of return json.dumps(dict) and then it sends special headers and JavaScript converts it to object and you can get response.volume. Using json.dumps(dict) it sends it as html/text and you would have to use JSON.parse(response).volume
Working code in one file (using template_render_string instead of template_render) so everyone can easily test it.
from flask import Flask, request, redirect, url_for, render_template, json, render_template_string, jsonify
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def control_panel():
print('request.form:', request.form)
if request.method == 'POST':
if request.form.get('button') == 'button-play':
print("play button pressed")
elif request.form.get('button') == 'button-exit':
print("exit button pressed")
elif request.form.get('slide'):
volume = request.form.get('slide')
print('volume:', volume)
#return jsonify({'volume': volume})
return json.dumps({'volume': volume})
print('render')
return render_template_string('''<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Slider</title>
</head>
<body>
<div class="container" id="control_panel_1">
<form action="/" method ="post" enctype="multipart/form-data" id="form">
<div class="row">
<div class="col">
<button class="btn btn-primary" button type="submit" name="button" value="button-play">PLAY</button>
<button class="btn btn-primary" button type="submit" name="button" value="button-exit">EXIT</button>
<input id="slide" type="range" min="1" max="100" step="1" value="10" name="slide">
<div id="sliderAmount"></div>
</div>
</div>
</form>
<!--- SCRIPTS --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
<script>
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
$.post({
url: '/',
data: $('form').serialize(),
success: function(response){
alert(response);
alert(response.volume); // works with jsonify()
alert(JSON.parse(response).volume); // works with json.dumps()
console.log(response);
},
error: function(error){
alert(response);
console.log(error);
}
});
}
</script>
</html>''')
if __name__ == '__main__':
app.run(debug=True, use_reloader=False)
I have a college assignment in which I need to create a small chatting web site. I'm using Python for the back-end code and Flask as the framework.
Basically, I want to get the user input from the front-end, run it with a Python code I developed, and send it back as an answer. How would be the easiest way to do that?
I've read a lot about jQuery and AJAX, but I'm very bad at JS. Any tips?
What I need is to,after processing this string, send to the site whatever was processed. I tried to follow this post How do I send data from JS to Python with Flask? and it worked for my POST, but not my GET. It always returns as undefined. I tried changing to dict, trying to make different calls, but I can't find what will work specifically with what I actually need. Thanks!
EDIT!:
After trying out #arsho 's code, I got kind of lost. It works and I saw how it was implemented, but couldn't exactly make it work with what I have.
This is what I came up with:
test
https://pastebin.com/4i2hDRSJ
Sorry if I'm not being very clear. I translated the variable names for easier understanding.
Pastebin with the html my friend made me:
test
https://pastebin.com/m7FQCgAm
Scripts.js:
test
https://pastebin.com/pM1L77p7
Thanks again.
I am giving a head start for your project. I am giving a simple AJAX search example using Flask.
The application.py contains:
from flask import Flask, render_template, request, url_for, redirect
app = Flask(__name__)
#app.route('/show_search_result', methods=['GET','POST'])
def show_search_result():
if request.method == "POST":
word = request.form.get("word")
word_lower = word.lower()
data = {
"name" : "Ahmedur Rahman Shovon",
"country": "Bangladesh",
"gender": "Male"
}
if word_lower in data:
value = data[word_lower]
return value
else:
return "No data found"
else:
return redirect(url_for('show_index'))
#app.route('/')
#app.route('/index')
def show_index():
return render_template("ajax.html")
if __name__ == '__main__':
app.run(debug=True)
And in ajax.html we call the ajax requests like below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="author" content="Ahmedur Rahman Shovon">
<title>Ajax Example</title>
<link href="https://fonts.googleapis.com/css?family=Exo+2:400,400i,500,500i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<!-- Font Awesome CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-10">
<div class="card bg-light mb-3 content">
<h5 class="card-header">
<i class="fa fa-globe"></i>
Search Developer's Information (e.g.: name, country, gender etc.)
</h5>
<div class="card-body message_area" id="message_area">
</div>
<div class="card-footer">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-book"></i>
</span>
<input type="text" class="form-control" id="search_word_text"
placeholder="Search a word and press enter"/>
<span class="input-group-btn">
<button class="btn btn-dark" id="search_btn" type="button">
<i class="fa fa-search"></i> Search
</button>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
function create_message_div($original_word, $ajax_data){
$html_data = "<div><p><b>Search Term: </b><i>"+$original_word+"</i></p>";
$html_data += "<p><b>Result: </b><i>"+$ajax_data+"</i></p>";
$html_data += "<hr/></div>";
return $html_data;
}
function search_word(){
$search_word_value = $("#search_word_text").val();
$("#search_word_text").val("");
$.ajax({
url: '{{ url_for("show_search_result") }}',
data: {
"word" : $search_word_value,
},
type: 'POST',
success: function(response) {
$new_div = create_message_div($search_word_value, response);
$("#message_area").prepend($new_div);
},
error: function(error) {
console.log("Error");
}
});
}
$("#search_btn").on("click", function () {
search_word();
});
$('#search_word_text').on('keypress', function (e) {
if(e.which === 13){
search_word();
}
});
})
</script>
</body>
</html>
The output:
N.B.: I have posted the full working code to show a complete view how AJAX works with Flask. Modify it as per your requirement.
I am expecting to get a simple line bokeh plot returned by Flask, but what I get when I browse to localhost:5002/simpleline is this:
('', '
')
I have two files. The Python file:
from bokeh.plotting import figure, show, output_file
from bokeh.embed import components
from flask import Flask, render_template
app=Flask(__name__)
#app.route('/simpleline/')
def simpleLine():
fig=figure(title="Sensor data")
fig.line([1,2,3,4],[2,4,6,8])
div=components(fig)
return render_template('simpleline.html',div=div)
show(fig)
if __name__ == "__main__":
app.run(debug=True,port=5002)
And the HTML template:
<!doctype html>
<html>
<head>
<title>Figure examples</title>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh-0.7.1.min.css" type="text/css" />
<script type="text/javascript"src="http://cdn.bokeh.org/bokeh-0.7.1.min.js"></script>
</head>
<body>
<div class='bokeh'>
{{ div|safe }}
</div>
</body>
</html>
I am sure I am missing something essential here.
After mn's answer, it was found out that components() produces two elements, a Javascript string, and an html div. So, I updated my scripts as follows, but this time the web page shows as blank.
from bokeh.plotting import figure, show, output_file
from bokeh.embed import components
from flask import Flask, render_template
app=Flask(__name__)
#app.route('/simpleline/')
def simpleLine():
fig=figure(title="Sensor data")
fig.line([1,2,3,4],[2,4,6,8])
global script
global div
script,div=components(fig)
return render_template('simpleline.html',div=div,script=script)
output_file("simpleline.html")
show(fig)
fig=figure(title="Sensor data")
fig.line([1,2,3,4],[2,4,6,8])
script,div=components(fig)
if __name__ == "__main__":
app.run(debug=True,port=5002)
And the HTML template:
<!doctype html>
<html>
<head>
<title>Figure examples</title>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh-0.9.0.min.css" type="text/css" />
<script type="text/javascript" src="http://cdn.bokeh.org/bokeh-0.9.0.min.js"></script>
{{ script|safe }}
</head>
<body>
<div class='bokeh'>
{{ div|safe }}
</div>
</body>
</html>
I tried all bokeh-0.7.1.min.js, 0.9, and 0.10, but I still got the same blank page.
components() returns (script, div) tuple with <script> that contains the data for your plot and an accompanying <div> tag that the plot view is loaded into:
http://docs.bokeh.org/en/latest/docs/user_guide/embed.html#components
script, div = components(fig)
return render_template('simpleline.html',div=div, script=script)
template
<!doctype html>
<html>
<head>
<title>Figure examples</title>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.10.0.min.css" type="text/css" />
<script type="text/javascript" src="http://cdn.bokeh.org/bokeh/release/bokeh-0.10.0.min.js"></script>
{{ script|safe }}
</head>
<body>
<div class='bokeh'>
{{ div|safe }}
</div>
</body>
</html>
Alternatively, you can also use autoload_static instead of components if you want the bokeh js and css to load automatically. Also you can save the js into a filepath and use only the div in the html to access it.
Here is a sample code that I worked with:
from bokeh.embed import autoload_static
from bokeh.resources import CDN
.............
.............
js, div = autoload_static(bar, CDN, '/static/bokeh/plot.js')
with open('static/bokeh/plot.js', 'w') as f:
f.write(js)
And then in the html file include only the div tag (includes the path of the js script).
<!doctype html>
<html>
<head>
<title>Figure examples</title>
</head>
<body>
<div class='bokeh'>
{{ div|safe }}
</div>
</body>
</html>