要传递参数,最好不要将它们作为 URI 的前缀,因为这可能会混淆 Flask 的路由解码。相反,如果您形成如下 URL
/plot.png?x=1,2,3,4&y=100,200,300,400
你可以通过以下方式获取参数request.args
。它们将以字符串形式出现,因此您需要将其分离并转换为整数(或浮点数,如果您使用实数)
from flask import request
@app.route('/plot.png')
def plot():
try:
x_values = [int(x) for x in request.args.get('x','').split(',')]
y_values = [int(y) for y in request.args.get('y','').split(',')]
except:
# malformed
我有一个工作示例here https://github.com/davewsmith/play/blob/master/matplotlib-flask/app.py动态处理 matplotlib 的稳健方法。总体思路是
from flask import send_file
@app.route('/plot.png')
def plot_png():
fig, ax = plt.subplots()
draw(ax)
return fig_response(fig)
def fig_response(fig):
"""Turn a matplotlib Figure into Flask response"""
img_bytes = BytesIO()
fig.savefig(img_bytes)
img_bytes.seek(0)
return send_file(img_bytes, mimetype='image/png')
你在哪里供应draw()
。不过,请看一下我的示例,因为您需要添加一些缓存标头。