How to add an HTTP header to all Django responses

2020-02-27 02:58发布

问题:

I'd like to add a few headers to all responses that my Django website returns. Is there a way to do this (besides adding a wrapper to the render function)?

回答1:

Yes, you should have a look at middlewares.

yourapp/middleware.py

class MyMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['X-My-Header'] = "my value"
        return response

yourproject/settings.py

MIDDLEWARE = [
    ...,
    'yourapp.middleware.MyMiddleware',
    ...,
]