2

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
5
  • I think you can check externally, print g.site whether it yields the right value?
    – Nava
    Sep 1, 2014 at 8:35
  • @Navaneethan Yes I can use that but I have some many views and I need something to use in all views like a after request to use it globally. also after request in not good either because at first the view function is processed.
    – hamidfzm
    Sep 1, 2014 at 8:55
  • where are you updating g.site?. How you are sure g.site == store, just try to print g.site and response.__dict__ first line of your function,you will get some idea.
    – Nava
    Sep 1, 2014 at 11:17
  • @Navaneethan I update g.site in app.before_request
    – hamidfzm
    Sep 1, 2014 at 11:28
  • @HamidFzM then why not return a 404 then?
    – Martijn Pieters
    Sep 1, 2014 at 23:37

1 Answer 1

4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.