最近,我有一個項目是實現網頁上的動態繪圖。如何刷新燒瓶網頁?
這裏是我的Python代碼
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')
這裏是我的HTML代碼
<!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>
雖然我添加<meta content='5; url=http://127.0.0.1:5000/plot' http-equiv='refresh'>
到我的HTML代碼,它仍然不能自動刷新。
如果我想觀察繪圖的變化,我仍然需要手動刷新它。
任何人都可以幫助我解決這個問題嗎?非常感謝
您可能想要參考這個答案: https://stackoverflow.com/questions/15721679/update-and-render-a-value-from-flask-periodically –
這與Python或Flask無關。最簡單的方法是使用頁面內的iframe,並定期更新它,或者更高級的(和正確的恕我直言)使用AJAX。檢查@LingchaoCao提供的鏈接。 –