Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

python - How to pass a variable between Flask pages?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.


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>

will produce the url:

/b?my_var=my_value

which can be read from b:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...