Python 如何在 Flask 页面之间传递变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27611216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:00:52  来源:igfitidea点击:

How to pass a variable between Flask pages?

pythonflask

提问by erogol

Suppose I have following case;

假设我有以下情况;

@app.route('/a', methods=['GET'])
def a():
  a = numpy.ones([10,10])
  ...
  return render_template(...) # this rendered page has a link to /b

@app.route('/b', methods=['GET'])
def b():
  print a
  ....

In the redered page there is one link that directs page /a to /b. I try to pass variable a to page /b to reuse it. How should I do this Flask app? Do I need to use session or is there any other solution?

在重新编辑的页面中,有一个将页面 /a 指向 /b 的链接。我尝试将变量 a 传递给 page /b 以重用它。我应该怎么做这个 Flask 应用程序?我需要使用会话还是有其他解决方案?

回答by davidism

If you want to pass some python value around that the user doesn't need to see or have control over, you can use the session:

如果你想传递一些用户不需要看到或控制的 python 值,你可以使用会话:

@app.route('/a')
def a():
    session['my_var'] = 'my_value'
    return redirect(url_for('b'))

@app.route('/b')
def b():
    my_var = session.get('my_var', None)
    return my_var

The session behaves like a dict and serializes to JSON. So you can put anything that's JSON serializable in the session. However, note that most browsers don't support a session cookie larger than ~4000 bytes.

会话的行为类似于 dict 并序列化为 JSON。因此,您可以在会话中放入任何 JSON 可序列化的内容。但是,请注意,大多数浏览器不支持大于 4000 字节的会话 cookie。

You should avoid putting large amounts of data in the session, since it has to be sent to and from the client every request. For large amounts of data, use a database or other data storage. See Are global variables thread safe in flask? How do I share data between requests?and Store large data or a service connection per Flask session.

您应该避免在会话中放入大量数据,因为每次请求都必须将其发送到客户端或从客户端发送出去。对于大量数据,请使用数据库或其他数据存储。请参阅烧瓶中的全局变量线程安全吗?如何在请求之间共享数据?存储每个 Flask 会话的大数据或服务连接



If you want to pass a value from a template in a url, you can use a query parameter:

如果要从 url 中的模板传递值,可以使用查询参数:

<a href="{{ url_for('b', my_var='my_value') }}">Send my_value</a>

will produce the url:

将产生网址:

/b?my_var=my_value

which can be read from b:

可以从 b 中读取:

@app.route('/b')
def b():
    my_var = request.args.get('my_var', None)

回答by Matt Healy

The link to route /bin the template for /acould have query parameters added to it, which you could read in the route for /b. Alternatively you could store the value for ain a session variable to access it between views.

/b模板中的路由链接/a可以添加查询参数,您可以在/b. 或者,您可以将 for 的值存储a在会话变量中以在视图之间访问它。