20

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?

1 Answer 1

26

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')
Sign up to request clarification or add additional context in comments.

3 Comments

I'm going to accept this answer. It's not exactly what I wanted but with some refactoring it actually does the job. I'll have to work with app.test_request_context() outside of the application but yeah, it will have to do. Thanks alot! =)
@moodh what solution did you end up with? This is something that I'm struggling with as well.
@ceolwulf: I made the configuration module useable without flask as well so I simply use from config import get_config and call config = get_config() every time I need it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.