Flask accessing config variables when app is created inside of function
Question:
I have the following configuration for my Flask application:
File Structure:
run.py
app/
__init__.py
views/
main/
__init__.py
main.py
...
__init__.py
def createpp():
app = Flask(__name__)
...
return app
main.py
...
key = app.config['KEY']
hashingID = hash(key)
@main.route('/', methods=['POST', 'GET'])
def main():
...
return render_template('main/main.html')
...
As you may see, I want to access app.config['KEY']
from main.py. The issue is, since app is configured inside of create_app()
, I cannot simply import it.
hashingID is always constant and is used in many different routes, otherwise I would have simply put
key = app.config['KEY']
hashingID = hash(key)
inside of the route.
Is there a way around this so that I can access config variables from an app instance that is generated inside a function? Thanks.
Answers:
It depends on what you’re trying to do.
You can see in this project where we create the Flask
instance inside a create_app
function, and then from that same function pass the app
variable into a number of other functions that perform our various configuration tasks.
The return value of the create_app
function is ultimately assigned to a top-level app
variable in the module, which can then be accessed in other modules by importing it as necessary (like here).
I have the following configuration for my Flask application:
File Structure:
run.py
app/
__init__.py
views/
main/
__init__.py
main.py
...
__init__.py
def createpp():
app = Flask(__name__)
...
return app
main.py
...
key = app.config['KEY']
hashingID = hash(key)
@main.route('/', methods=['POST', 'GET'])
def main():
...
return render_template('main/main.html')
...
As you may see, I want to access app.config['KEY']
from main.py. The issue is, since app is configured inside of create_app()
, I cannot simply import it.
hashingID is always constant and is used in many different routes, otherwise I would have simply put
key = app.config['KEY']
hashingID = hash(key)
inside of the route.
Is there a way around this so that I can access config variables from an app instance that is generated inside a function? Thanks.
It depends on what you’re trying to do.
You can see in this project where we create the Flask
instance inside a create_app
function, and then from that same function pass the app
variable into a number of other functions that perform our various configuration tasks.
The return value of the create_app
function is ultimately assigned to a top-level app
variable in the module, which can then be accessed in other modules by importing it as necessary (like here).