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?

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
moodh
  • 2,661
  • 28
  • 42

1 Answers1

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')
Rachel Sanders
  • 5,734
  • 1
  • 27
  • 36
  • 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 Nov 19 '12 at 23:06
  • @moodh what solution did you end up with? This is something that I'm struggling with as well. – Patrick May 11 '13 at 03:18
  • 3
    @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 :) – moodh May 11 '13 at 12:22