user11125012
user11125012

Reputation:

Flask `app.before_request` when using a factory function?

the docs suggest using factory function.

def create_app():
    app = Flask(__name__)
    return app()

so I don't have access to my app when I'm writing my code,
for this porpuse there is an object called " current_app " in flask module,
so I did this and I got " out of application context error "

@current_app.before_request
def before_req():
    whatever...

how can I define before request functions when I'm using a factory function?!

Upvotes: 2

Views: 1846

Answers (1)

vremes
vremes

Reputation: 674

You can define your before_request function inside create_app function:

def create_app():
    app = Flask(__name__)

    @app.before_request
    def before_request(response):
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response

    return app

If you use Flask Blueprints, you define before_request function for your blueprint like this:

from Flask import Blueprint

my_blueprint = Blueprint('my_blueprint', __name__)

@my_blueprint.before_request
def before_request(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

Upvotes: 4

Related Questions