Flask webserver run with waitress is not using before_request, only before_app_request

22 Views Asked by At

I used to have this working:

auth.py

bp = Blueprint("auth", __name__)

@bp.before_app_request
def validate_token():
    # code
    session["user"] = user

index.py

@bp.route("/user")
def get_user():
    return make_response(session["user"], 200)

However, after implementing tests to the application, before_app_request was being called and since the testing agent is not authenticated (nor should they be), it'd break. Changing to before_request seemed to fix the problem. In fact, it works fine when I run it with flask --app app_name run --debug. However, I deploy it to production using waitress. Running waitress-serve --port 8081 --host 0.0.0.0 --call app_name:create_app, the before_request is never called, resulting in an error.

1

There are 1 best solutions below

0
Masamune On

For future reference: before_request is called before each request within the blueprint. To solve my error I had to keep the before_app_request and check if on the app config "testing" was true:

from flask import current_app as app

@bp.before_app_request
def validate_token():
    if app.testing:
        return
    #code

Not pretty but got the job done.