【问题标题】:How does function decorated with `route()` from flask receives arguments?用烧瓶中的`route()`装饰的函数如何接收参数?
【发布时间】:2020-03-04 12:28:09
【问题描述】:

我正在用烧瓶绘制一个 Matplotlib 图:

@app.route('/plot.png')
def plot_png():
    x = range(100)
    y = np.random.randint(0,100,100)
    fig = create_figure(x,y)
    output = io.BytesIO()
    FigureCanvas(fig).print_png(output)
    return flask.Response(output.getvalue(), mimetype='image/png')

有效
但我需要将参数提供给 plot_png:

@app.route('/plot.png/<y>/')
def plot_png(y):
    x = np.arange(len(y))
    fig = create_figure(x,y)
    output = io.BytesIO()
    FigureCanvas(fig).print_png(output)
    return flask.Response(output.getvalue(), mimetype='image/png')

不起作用。

如何将参数提供给 plot_png?
谢谢!

【问题讨论】:

  • 尝试从 URL 中删除结尾的 /。否则语法是正确的。
  • @chepner 我得到了ValueError: urls must start with a leading slash
  • 尾随,而非前导:'/plot.png/&lt;y&gt;'
  • @chepner 对此感到抱歉。不适用于'/plot.png/&lt;ys&gt;'
  • “不工作”是什么意思?您是收到错误消息,还是根本没有调用 plot_png

标签: python matplotlib flask routes decorator


【解决方案1】:

正如所写,y 将是一个字符串。

@app.route('/plot.png/<int:y>')

会解决这个问题。如果需要,请添加尾部斜杠。

【讨论】:

  • 我仍然收到"GET /plot.png HTTP/1.1" 404 -
  • 那是因为您没有与之匹配的@app.route()flask.palletsprojects.com/en/1.1.x/quickstart(在渲染模板中)中有一个示例可能会有所帮助。
  • 谢谢。 @app.route() 不匹配什么?
  • 如果您定义了两次plot_png,第二次将覆盖第一次。某些语言会将plot_png()plot_png(y) 视为单独的函数/方法。 Python 没有。
猜你喜欢
  • 2018-02-17
  • 2018-10-08
  • 2012-07-14
  • 2013-08-21
  • 2019-01-06
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多