Question

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?

Was it helpful?

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.

OTHER TIPS

You might consider just writing a custom WSGI middleware. You can snag all of your application's responses and augment the headers as necessary. The quickstart discusses how to hook in a middleware and there are no shortage of WSGI tutorials on how to add headers to the start_response

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top