8

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

陳俊良
  • 319
  • 1
  • 6
  • 13
  • You might wanna refer to this answer: https://stackoverflow.com/questions/15721679/update-and-render-a-value-from-flask-periodically – Lingchao Cao Aug 14 '17 at 03:04
  • This has nothing to do with Python or Flask. Simplest approach would be using `iframe` within page and regularly updating it, or more advanced (and correct IMHO) to use AJAX. Check the link provided by @LingchaoCao. – Andrejs Cainikovs Aug 14 '17 at 08:02

1 Answers1

7

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.

Nabin
  • 11,216
  • 8
  • 63
  • 98
  • 2
    But be aware that websockets often does not work behind corporate firewalls. I recommend using AJAX instead. – Andrejs Cainikovs Aug 14 '17 at 08:06
  • Are you sure, refreshing on every X interval to see the changes is good approach? May be pooling is better option. Also there has to be a workaround in corporate firewalls. @AndrejsCainikovs Right? :) – Nabin Aug 14 '17 at 08:07
  • 2
    resource-wise websockets are efficient, access-wise AJAX is the safest. I experience websocket denial at my work, and I suffer in pain quite often. And since all the corporate network is configured properly, I cannot do anything about this. In any case - these are just my 0.02$. – Andrejs Cainikovs Aug 14 '17 at 08:15
  • @AndrejsCainikovs Thank you for the discussion. Got some info from you. Hope this helps everyone. Cheers!! – Nabin Aug 14 '17 at 09:11
  • Thanks for your advise, I will try these – 陳俊良 Aug 14 '17 at 12:07