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
Launch your browser. Go to app/extension store (Chrome Web Store, Firefox Add-Ons, Microsoft Edge Add-ons Store, etc.). Enter “auto-refresh” in the search bar. Choose an extension.
To refresh a web page using the selenium module in Python, we use the refresh() function. This is shown in the code below. The refresh() will refresh the web page, acting just like the refresh button of a web browser or clicking the 'F5' button on your keyboard.
To run the app outside of the VS Code debugger, use the following steps from a terminal: Set an environment variable for FLASK_APP . On Linux and macOS, use export set FLASK_APP=webapp ; on Windows use set FLASK_APP=webapp . Navigate into the hello_app folder, then launch the program using python -m flask run .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With