Nick Mueller
Nick Mueller

Reputation: 121

Configure Email Token with Flask Factory Application create_app

I am getting confused with configurations and imports once I started using the Flask factory application pattern.

I am creating an application with the function create_app in #app/init.py I have a config file for setting the development/testing/production variables, and an instance folder with another config file.

def create_app(config_name):
    app=Flask(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    etc...
    return app

I am using blueprints and have an authentication view in #app/auth/views.py I am trying to set up email confirmation tokens using URLSafeTimedSerializer...

from itsdangerous import URLSafeTimedSerializer

@auth.route('/register', methods=['GET','POST'])
def register():
    ts = URLSafeTimedSerializer(app.config['SECRET_KEY'])
    token = ts.dumps(self.email, salt='email-confirm-key')
    etc...

Now my problem is, my variable 'ts' needs the app.config['SECRET_KEY'] set. But I am unable to define the app variable (as is shown in all online tutorials). I get an error when I try to import...(in #app/auth/views.py)

from .. import app

and when I try to import like...

from .. import create_app

Can someone shine light on how to initialize modules using 'app' and app.config outside the flask app factory create_app?

Hope you understand my question.

Upvotes: 0

Views: 796

Answers (1)

Matt Healy
Matt Healy

Reputation: 18521

In this scenario you should use Flask.current_app

from flask import current_app

...

ts = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])

From the documentation:

flask.current_app

Points to the application handling the request. This is useful for extensions that want to support multiple applications running side by side. This is powered by the application context and not by the request context, so you can change the value of this proxy by using the app_context() method.

This link aso explains further details about the Flask application factory methodology, in particular using current_app to access the app configuration.

Upvotes: 1

Related Questions