如何在 Flask 页面之间传递变量? [英] How to pass a variable between Flask pages?

查看:27
本文介绍了如何在 Flask 页面之间传递变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下案例;

@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
  ....

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

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?

推荐答案

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

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:

@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

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

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.

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

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.

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

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

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

将产生网址:

/b?my_var=my_value

可以从b中读取:

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

这篇关于如何在 Flask 页面之间传递变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆