5

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 View 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 route decorator and would have to use its surrogate function add_url_rule.

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)
        print(x)
    
    def baz():
        return someMadeupFunction(x)
    
  2. def foo():
        x = request.form["fizz"]
        qux(someValue)
    
    def qux(i):
        menu = {
        key0: bar,
        key1: baz,
        }
        menu[i](x)
    
    def bar(x):
        # do something with x (readable)
        print(x)
    
    def baz(x):
        return someMadeupFunction(x)
    
2
  • 3
    Aside: there is no reason why a project needs to be "large" or "complex" before you consider using classes. Commented Jul 5, 2016 at 0:56
  • Very true, however this is my first project using the Flask API, and i'm teaching myself as I go. I hope to convert this to class base in the future however as a learning exercise. Commented Jul 5, 2016 at 0:57

1 Answer 1

6

I believe what you are looking for is the application local g. According to the documentation

Just store on this whatever you want.

It meets your needs here exactly.

from flask import g

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

def bar():
    # do something with x (readable)
    print(g.x)

def baz():
    return someMadeupFunction(g.x)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.