By erogol

2014-12-22 22:11:18 8 Comments

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?


@davidism 2014-12-22 22:17:13

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:

def a():
    session['my_var'] = 'my_value'
    return redirect(url_for('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:


which can be read from b:

def b():
    my_var = request.args.get('my_var', None)

@Matt Healy 2014-12-22 22:17:42

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

Related Questions

Sponsored Content

22 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 3460830 View
  • 3474 Score
  • 22 Answer
  • Tags:   python directory

23 Answered Questions

[SOLVED] What is the difference between @staticmethod and @classmethod?

30 Answered Questions

[SOLVED] How do I check if a list is empty?

  • 2008-09-10 06:20:11
  • Ray Vega
  • 2362903 View
  • 3235 Score
  • 30 Answer
  • Tags:   python list

37 Answered Questions

[SOLVED] How do I check whether a file exists without exceptions?

18 Answered Questions

[SOLVED] Using global variables in a function

41 Answered Questions

[SOLVED] How to merge two dictionaries in a single expression?

20 Answered Questions

22 Answered Questions

[SOLVED] Difference between __str__ and __repr__?

26 Answered Questions

[SOLVED] How do I pass a variable by reference?

34 Answered Questions

[SOLVED] How do I sort a dictionary by value?

Sponsored Content