Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh the flask web page?

Tags:

python

html

flask

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

like image 533
陳俊良 Avatar asked Aug 14 '17 02:08

陳俊良


People also ask

How do you refresh a page automatically in flask?

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.

How do you refresh a page in webbrowser Python?

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.

How do I set my flask to run?

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 .


1 Answers

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.

like image 134
Nabin Avatar answered Sep 23 '22 00:09

Nabin