Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
beardc Avatar asked Apr 17 '14 15:04

beardc


Video Answer


2 Answers

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.

like image 190
Martijn Pieters Avatar answered Oct 18 '22 04:10

Martijn Pieters


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

like image 29
nsfyn55 Avatar answered Oct 18 '22 06:10

nsfyn55