[英]How to show chart with data from html form on the same page using python and flask
我正在學習並被卡住了。 我想構建一個超級簡單的 Web 應用程序,它獲取一些數據(2 個值)並將它們繪制在餅圖中。 到目前為止它的工作(從表單中獲取數據,創建繪圖並將其打印在.../plot.png 上)但我想在與表單相同的頁面上顯示圖表,我只是猜測。
我想我需要以某種方式以動態方式將圖表鏈接到 /home html,但我不知道該怎么做。 我看到了很多類似的問題,但他們中的大多數都使用 js,我想保持簡單,只使用 Flask。
主要.py:
from flask import request
import io
#import random
from flask import Response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
#from matplotlib.figure import Figure
import matplotlib.pyplot as plt
app = Flask(__name__)
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Aprovechado', 'Vertido'
explode = (0, 0)
@app.route('/plot.png')
def plot_png():
fig = create_figure()
output = io.BytesIO()
FigureCanvas(fig).print_png(output)
return Response(output.getvalue(), mimetype='image/png')
def create_figure():
autoconsumo = request.args.get('autoconsumo')
vertido = request.args['vertido']
sizes = [autoconsumo, vertido]
fig, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
return fig #render_template("autoconsumo.html") #fig
@app.route("/")
def home():
return render_template("home.html")
if __name__ == "__main__":
#plot_png()
app.run(debug=True)
主頁.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Flask Tutorial</title>
</head>
<body>
<h1> My First Try Using Flask </h1>
<form action="/plot.png">
Autoconsumo <input type='number' name='autoconsumo'><br>
Vertido <input type='number' name='vertido'><br>
<input type='submit' value='Continue'>
</form>
<p> Flask is Fun </p>
<img src="/plot.png?autoconsumo="'autoconsumo'"&vertido="'vertido' alt="my plot"> #<= I think its about this line
</body>
</html>
我在閱讀您所說的without Javascript
的部分之前寫了這個答案,但無論如何我都會發布這個。 如果您真的想要一個只涉及 Flask 的答案,請告訴我。
一個非常簡單的方法是在你的form
、 input
和img
標簽中添加一些id
屬性:
<form id='plot'>
Autoconsumo <input type='number' id='autoconsumo' /><br />
Vertido <input type='number' id='vertido' /><br />
<input type='submit' value='Continue' />
</form>
<img id='img' alt="my plot">
然后立即添加一些 javascript 來獲取這些元素,然后更改表單提交時的圖像源:
<script type='text/javascript'>
const form = document.getElementById('plot');
const autoconsumo = document.getElementById('autoconsumo');
const vertido = document.getElementById('vertido');
const img = document.getElementById('img');
// Event listener which changes the image src attribute on form submit:
document.addEventListener('submit', function(e){
e.preventDefault(); // Stops submit button from moving to new page
img.src = '/plot.png?autoconsumo=' + autoconsumo.value + '&vertido=' + vertido.value;
});
</script>
</body>
其他人可能有更優雅的解決方案,但這是有效的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.