Philippe Remy
Philippe Remy

Reputation: 3123

Initializing objects used in routes with Flask

I am using Flask server and I would like to initialize some objects and make them visible for the routes.

Not to have too much code between the imports and the definitions of the routes would be great.

What is the best way to do that? Here is an example with an object called Object. This example works but I'm sure there's a better way to do this.

Maybe giving some arguments to Flask(__name__) works but not sure how to do that.

from flask import Flask

# Could I give some references of the object o here?
app = Flask(__name__) 


class Object:
    def __init__(self):
        self.value = 2


# I would like to avoid stuffing too much code between 
# the imports and the definitions of the routes.
o = Object() 


@app.route('/')
def hello_world():
    # I need the object to be in this scope. 
    # Maybe with app.o or something similar?
    return f'Hello, World! {o.value}'


if __name__ == '__main__':
    # Ideally the definition of o = Object() goes here and app exposes it.
    app.run()

Upvotes: 2

Views: 3479

Answers (1)

Jürgen Gmach
Jürgen Gmach

Reputation: 6123

Your current way is exactly that what I would do when I start a Flask app. As long as the app is not too big, keep it simple in one file.

Depending where you need your o, you could instantiate it directly in your routes.

If your application grows, you could move you "data provider" into a separate module and import from there.

About your inline questions / comments:

# Could I give some references of the object o here?
app = Flask(__name__) 

No. You can pass in a separate template dir or similar, but no data for routes.

# I would like to avoid stuffing too much code between 
# the imports and the definitions of the routes.
o = Object() 

As suggested, this is ok for now, if it gets too much code, move it to another module and import from there.

@app.route('/')
def hello_world():
    # I need the object to be in this scope. 
    # Maybe with app.o or something similar?
    return f'Hello, World! {o.value}'

You could also instantiate the "data source" object here in the route.

if __name__ == '__main__':
    # Ideally the definition of o = Object() goes here and app exposes it.
    app.run()

Don't put any more code in here, as it is very hard to test (if you start to write tests).

Upvotes: 3

Related Questions