How to refresh the flask web page? - python

Recently, I have a project is to implement the dynamic plotting on a web page.
Here is my python code
from flask import Flask
#from flask import render_template
import matplotlib.pyplot as plt
import io
import base64
app = Flask(__name__)
#app.route('/plot')
def build_plot():
img = io.BytesIO()
y = [1,2,3,4,5]
x = [0,2,1,3,4]
plt.plot(x,y)
plt.savefig(img, format='png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()
return '<img src="data:image/png;base64,{}">'.format(plot_url)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<title> Plot</title>
<meta content='5; url=http://127.0.0.1:5000/plot' http-equiv='refresh'>
</head>
<body>
<img src="data:image/png;base64, {{ plot_url }}">
</body>
</html>
Although I add <meta content='5; url=http://127.0.0.1:5000/plot' http-equiv='refresh'> into my HTML code, it still can not refresh automatically.
If I want to observe the change of the plotting, I still need to refresh it manually.
Can anyone help me to solve this problem? Thanks a lot

You do not need to include the URL. Just use only the content attribute of meta tag.
<meta http-equiv="refresh" content="5" >
But to see the real time changes in your graph, you might want to look at sockets in flask. This will help server push changes to all clients using broadcasting. Using sockets is way better approach than to refresh your page at regular interval.

Related

Flask refresh on new file

I am trying to figure out how to use flask to just show a simple image and update with a new image. I have the following that seems to work just fine for images (pretty much right from MPL website):
#app.route("/image")
def show_image():
to_show = do_stuff(os.listdir( current_dir )[-1] ) #turn file into 2d np.array
fig, ax = plt.subplots()
ax.imshow( to_show, **plot_pars)
buf = BytesIO()
fig.savefig(buf, format = "png")
plot_url = base64.b64encode(buf.getvalue().decode("utf8")
return render_template("index.html", plot_url = plot_url)
The index.html file is currently setup to refresh every 15 seconds
<!DOCTYPE html>
<html>
<head>
<title> Plot</title>
<meta http-equiv='refresh' content="15>
</head>
<body>
<img src="data:image/png;base64, {{ plot_url }}">
</body>
</html>
I am curious if I can set something up that will basically run show_image if the length of my current_dir changes. If I try it in my show_image function (if os.listdir( current_dir) != nfiles ), but nothing changes, so I am trying to figure out the best way to start with this "trigger".

Correct way of hard-coding html code in python script?

I have developed a web-based tool, and currently trying to make it python-launchable. I figured using CEFpython is probably the way to do it. I followed the tutorial here and wrote the following code:
from cefpython3 import cefpython as cef
import base64
import platform
import sys
import threading
import os
HTML_code = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link href="static/css/main.css" rel="stylesheet" />
</head>
<body>
<div id="UI">
</div>
<div id="container"></div>
<script src="static/main.js"></script>
<script type="text/javascript">
function defineData(datainput){
console.log("start")
data = datainput;
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
console.log(loc);
console.log(dir);
Main();
}
</script>
</body>
</html>
"""
def html_to_data_uri(html):
html = html.encode("utf-8", "replace")
b64 = base64.b64encode(html).decode("utf-8", "replace")
ret = "data:text/html;base64,{data}".format(data=b64)
return ret
def main(config):
sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error
settings = {}
cef.Initialize(settings=settings)
browser = cef.CreateBrowserSync(url=html_to_data_uri(HTML_code),window_title="Test")
browser.SetClientHandler(LoadHandler(config))
cef.MessageLoop()
cef.Shutdown()
return
class LoadHandler(object):
def __init__(self, config):
self.config = config
def OnLoadingStateChange(self, browser, is_loading, **_):
"""Called when the loading state has changed."""
if not is_loading:
# Loading is complete. DOM is ready.
browser.ExecuteFunction("defineData", self.config)
unfortunately, unlike in the tutorial, my tool has to load a local .js file where the main function is defined (), and it seems if I code the html file this way, my working directory is not actually the directory where I call the script, but some strange place
the output of these lines are:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
console.log(loc);
console.log(dir);
output:
text/html;base64,CjwhRE9DVFlQRSBodG1sPgo8aHRtbCBsYW5nPSJlbiI+Cgk8aGVhZD4KCQk8bWV0YSBjaGFyc2V0PSJ1dGYtOCI+CgkJPG1ldGEgbmFtZT0idmlld3BvcnQiIGNvbnRlbnQ9IndpZHRoPWRldmljZS13aWR0aCwgdXNlci1zY2FsYWJsZT1ubywgbWluaW11bS1zY2FsZT0xLjAsIG1heGltdW0tc2NhbGU9MS4wIj4KCQk8bGluayBocmVmPSJzdGF0aWMvY3NzL21haW4uY3NzIiByZWw9InN0eWxlc2hlZXQiIC8+CgkJPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCQkJKiB7CgkJCQkuYm9yZGV....
text
Could you help me finding the correct way of hard coding html code in python with the correct path? maybe I need to somehow set the path?
PS: I did try including the html code in a separate .html file, and it worked on Windows machines, but it seems MacOS doesn't like it. Since this tutorial did work on MAC, I'm trying to hard code the html part into the python script and hope it would work on both Windows and Mac
Well, the HTML document has been converted to the body of a data URI by html_to_data_uri, so the U[niversal]R[esource]L[ocator] (window.location) of the document isn't a location on a server, but the data URI itself (the "strange place" you mention).
Remember that URLs are a subset of URIs, and you passed the URI as a URL to CEF with:
browser = cef.CreateBrowserSync(url=html_to_data_uri(HTML_code),window_title="Test")
So, as long as you are using a data URI/URL, I don't think that window.location will be helpful. Instead, you could extract the HTML code into a separate .html file, and change that line to:
browser = cef.CreateBrowserSync(url="/path/to/that_html_file.html", window_title="Test")

Can Bottle's rebase() and include() be made to run from templates in memory?

I can get rebase() and include() to work with templates files on disk using rebase("base_template.tpl"), but am not seeing how to get this to run with templates stored in memory.
Here is my current effort:
from bottle import template
base_template = '''\
<html>
<head>
<title>{{title or 'No title'}}</title>
</head>
<body>
{{!base}}
</body>
</html>
'''
inner_template = '''\
% rebase(base_template, title='Page Title')
<p>Page Content ...</p>
'''
print(template(inner_template, base_template=base_template))
The above code results in a TemplateError.
Looks like it's a known issue with bottle, and this discussion https://github.com/bottlepy/bottle/issues/521 mentions a workaround.
However, no clues if it's working or not with latest version.

Python code to change the background color of html

I have created a dashboard using python. I have a requirement to make some cosmetic changes in the html page.
Change the font and size
Changing the background color
Putting one company logo.
I researched with turtle and tkinter,and installed the same but the system is not recogonizing the modules. Is there a way to achieve the above functionality.
Source code is as below
#!/usr/local/bin/python
import requests
import json
import datetime
import sys
import os
from html import HTML
todayDate=datetime.date.today().strftime("%Y-%m-%d")
h=HTML('html','')
p=h.p('DETAILS for ',' ', todayDate)
t=h.table(border='1')
r=t.tr()
r.td('Import Timestamp')
r.td('JobId')
r.td('Status')
r.td('RecordsProcessed')
r.td('RecordsFailed')
r.td('FileName')
r.td('Duration')
r.td('Throughput')
print '\n'
def genHTMLforImportSuccess():
responseurl = requests.get(url)
if(responseurl.ok):
jData = json.loads(responseurl.content)
if jData > 0:
for responseurl in jData['response']:
starttime=responseurl['statistics']['startTime']
jobId= responseurl['jobId']
status = responseurl['status']
recordsProcessed=responseurl['statistics']['recordsProcessed']
recordsFailed=responseurl['statistics']['recordsFailed']
fileName=responseurl['fileName']
duration=responseurl['statistics']['duration']
throughput=responseurl['statistics']['throughput']
print '\n'
r=t.tr()
r.td(str(starttime))
r.td(str(jobId))
r.td(str(status))
r.td(str(recordsProcessed))
r.td(str(recordsFailed))
r.td(str(fileName))
r.td(str(duration))
r.td(str(throughput))
print '\n'
else:
print "No data feed"
else:
responseurl.raise_for_status()
genHTMLforImportSuccess()
print h
Any help is highly appreciated
I added the below code after the
from html import HTML
html = """
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>testpage </title>
<style>
body {
background-color: aqua;
}
</style>
</head>
<body>
</body>
</html>
"""
but could not get the desired result.how can i fix this

How to insert data to HTML page with Python?

I have some data and I would like to write it into an HTML page.
In PHP in would be possible just to write
<?php .... take the data and print it ?>
How can it be done with Python?
Should I generate the WHOLE page with Python or can I just extract this data and place it in the needed place in the HTML page?
This should be accessed from a web server when someone requests a URL.
If you use a framework like Flask or Django, you can use templates to render data into HTML without having to print out the entire HTML from Python (actually, it does that behind-the-scenes, but you only have to write your template once).
Flask uses a templating language called Jinja2, which lets you write templates like this:
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
Hello, {{ name }}.
</body>
</html>
and render them out like this:
#app.route('/index')
def index():
title = "My Page"
name = "Foo"
return render_template('mytemplate', title=title, name=name)
Django has a similar function with its inbuilt templating system.
If you are running on a cheap webhost, you might not have the flexibility for running a full-blown web framework like Django or Flask (which have a lot of dependencies and should be run in a WSGI server). On my webhost, Siteground, I use a microframework called Bottle.py, which is similar to Flask but has only a single-file dependency so it can run wherever Python is running, using CGI. I have it set up as detailed in this post, by running it as CGI—app.run(server='cgi')—and use .htaccess rules with mod_rewrite to remove the app.py from the URL.
Documentation: https://pypi.python.org/pypi/html/
Do like this:
print("Content-type: text/html\n")
print("""<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Обработка данных форм</title>
</head>
<body>""")
print("<h1>Обработка данных форм!</h1>")
print("<p>TEXT_1: {}</p>".format(text1))
print("<p>TEXT_2: {}</p>".format(text2))
print("""</body>
</html>""")
You can push the data to mysql and fetch that using php code.
python code for pushing to mysql
php code for fetching from mysql

Categories

Resources