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()