Search code examples
pythonflaskdecoratorpython-decorators

How to apply decorator to every Flask view


I have a decorator (call it deco) that I would like to apply to every view in my Flask app, in order to modify the response headers to avoid IE's compatibility mode (res.headers.add("X-UA-Compatible", "IE=Edge"). I use it like

@app.route('/')
@deco
def index():
    return 'Hello world'

I currently use a subclass of Flask to create the app (to modify jinja behavior)

class CustomFlask(Flask):
    jinja_options = ...

app = CustomFlask(__name__, ...)

Is there a way I can modify CustomFlask to apply deco decorator to all the responses?


Solution

  • To add headers to every outgoing response, use the @Flask.after_request hook instead:

    @app.after_request
    def add_ua_compat(response):
        response.headers['X-UA-Compatible'] = 'IE=Edge'
        return response
    

    There is a Flask extension that does exactly this; register the hook and add a header.