Pav Sidhu
Pav Sidhu

Reputation: 6944

Access config values in Flask from other files

I have the following app structure:

manage.py
myapp/
  __init__.py
  config.py
  views/
    __init__.py
    login.py
    ...

In myapp/__init__.py I have a function create_app() which returns the Flask app instance. The config values are also stated in create_app() too. I would like to be able to access these values in other files such as login.py. I've tried:

from myapp import create_app as app
print app.config['SECRET_KEY']

However I receive an error stating AttributeError: 'function' object has no attribute 'config'

What am I doing wrong and how can I fix this? Thanks.

Upvotes: 32

Views: 35791

Answers (4)

Nirbhay Rana
Nirbhay Rana

Reputation: 4347

Create the app with app context and init your db and other dependencies

def create_app():
app = Flask(__name__, static_folder="assets")
cfg = import_string(environ.get('PROFILE'))()
app.config.from_object(cfg)

with app.app_context():
   init_db()

then you can use

from flask import current_app

def init_db(self):
  mongo_client = MongoClient(current_app.config['DATABASE_URI'])

Upvotes: 0

Logan Cundiff
Logan Cundiff

Reputation: 553

Two scenerios:

1. Your code is within app scope:

Add this to top of your file from flask import current_app

To access variables saved to your app config: current_app.config['SECRET_KEY'] or current_app.config.get('SECRET_KEY')

Make sure you called app.config.from_object(config) in your app or _init_ py file or initialize your app.config in a different manner.

2. Your code is outside app scope or it is being compiled before app is initialized. There are a few options.

a. Import your secret key from your environment.

import os

SECRET_KEY = os.getenv("SECRET_KEY", "defaultSecret")

b. Import your secret key from a local file:

from local import config

SECRET_KEY = config.get("SECRET_KEY")

Where local is the file that contains your configuration class.

Upvotes: 0

Jdougie
Jdougie

Reputation: 21

This worked for me, for the next person that needs this. I had a similar setup from the tutorials.

from myapp import create_app

app = create_app()
print app.config['SECRET_KEY']

Upvotes: 1

goodcow
goodcow

Reputation: 4795

Use from flask import current_app. You define SECRET_KEY in settings.py.

print current_app.config['SECRET_KEY']

Upvotes: 65

Related Questions