Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to import flask configuration values in modules without circular import?

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?

like image 654
moodh Avatar asked Nov 19 '12 13:11

moodh


People also ask

How do you stop circular imports in Flask?

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.

Why can't I import a Flask?

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.

What does app config to Flask?

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.

Is Flask a module or package?

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.


1 Answers

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')
like image 82
Rachel Sanders Avatar answered Oct 14 '22 23:10

Rachel Sanders