I'm using Flask with Blueprints to get a skeleton for my website and I'm having a problem using configuration classes deep in my application.
Here's some dummy code that explains how I've set everything up:
websiteconfig.py
class Config(object):
pass
class ProductionConfig(Config):
DEBUG = False
class DevelopmentConfig(Config):
DEBUG = True
website/__ init __.py:
# Some app code and config loading
app = Flask('website')
app.config.from_object('websiteconfig.DevelopmentConfig')
# Import some random blueprint
from website import users
app.register_blueprint(users.api)
# This works:
# print app.config['DEBUG']
website/users/__ init __.py:
from flask import Blueprint
from website.users.models import test
api = Blueprint('users', __name__, url_prefix='/users')
# This works:
# print api.config['DEBUG']
# From models
print test()
website/users/models.py:
# How can I reach the config variables here?
def test():
# I want config['DEBUG'] here
How can I reach the configuration variables stored in the class I load in app.py
deep inside the users
package?
Is a circular import like from website import app
(inside models.py) an accepted solution?
If not, is there some simple solution I've missed?
At the same time, there is a risk that cyclic imports will occur and it will be difficult to maintain a project. Flask documentation and basic tutorials suggest to write a project initialization code in __init__.py to solve the problem. This code creates Flask instance of a class and configures an app.
The Python error "ModuleNotFoundError: No module named 'flask'" occurs for multiple reasons: Not having the Flask package installed by running pip install Flask . Installing the package in a different Python version than the one you're using. Installing the package globally and not in your virtual environment.
When your app is initialized, the variables in config.py are used to configure Flask and its extensions are accessible via the app. config dictionary – e.g. app. config["DEBUG"] . Configuration variables can be used by Flask, extensions or you.
Flask is a web framework, it's a Python module that lets you develop web applications easily. It's has a small and easy-to-extend core: it's a microframework that doesn't include an ORM (Object Relational Manager) or such features.
I believe you can use flask's current_app idiom for that.
http://flask.pocoo.org/docs/api/#flask.current_app
from flask import current_app
def test():
return current_app.config.get('some_config_value')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With