Joseph Joseph - 3 months ago 8x
Python Question

Share data across Flask view functions

I am using Flask to build a very small one-page dynamic website. I want to share a list of variables and their values across functions without using a class.

I looked into Flask's

class, however I feel as if my application isn't large enough nor complex enough to implement a class-based version of my project using Flask. If I'm stating correctly I would also lose the ability to use the
decorator and would have to use its surrogate function

Which would also force me to refactor my code into something such as this:

from flask.views import View
class ShowUsers(View):

def dispatch_request(self):
users = User.query.all()
return render_template('users.html', objects=users)

app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users'))

For variable sharing I thought of two techniques.

  1. x = ""

    def foo():
    global x
    x = request.form["fizz"]

    def bar():
    # do something with x (readable)

    def baz():
    return someMadeupFunction(x)

  2. def foo():
    x = request.form["fizz"]

    def qux(i):
    menu = {
    key0: bar,
    key1: baz,

    def bar(x):
    # do something with x (readable)

    def baz(x):
    return someMadeupFunction(x)


I normally just add them as methods to app as in app.x = request.form["fizz"]. All of your routes should have access to this as long as your app declaration above the route definitions.