Abort 404 not working in flask after request

Question:

I have a multi domain website with flask but I want to restrict access to all views and blueprints except those I allowed access to them in some domains. So I decided to use flask after request decorator to do that but the problem is abort is not working in flask after request. What is the problem?

This is my sample code:

@app.after_request
def restricted_access(response):
    if g.site == 'store':
        return abort(404)
    return response
Asked By: hamidfzm

||

Answers:

abort(404) raises an exception, it doesn’t return the response object. But since after_request functions are executed after the normal view handling and outside the exception handler the NotFound exception raised will not be handled.

You could re-use the exception handler normally applied to views that raise an exception:

from werkzeug.exceptions import NotFound

@app.after_request
def restricted_access(response):
    if g.site == 'store':
        return current_app.make_response(
            current_app.handle_user_exception(NotFound()))
    return response

The handle_user_exception() method does return a response object.

That said, if you already know g.site‘s value in a before_request() handler, it’ll be a lot easier to return a 404 then and there; you can safely use a abort(404) in a before_request() handler.

Answered By: Martijn Pieters