How to add an HTTP header to all Django responses

2020-02-27 02:22发布

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条回答
可以哭但决不认输i
2楼-- · 2020-02-27 03:17

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',
    ...,
]
查看更多
登录 后发表回答