Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an HTTP header to all Django responses

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)?

like image 326
Cisplatin Avatar asked Mar 19 '16 07:03

Cisplatin


People also ask

How do I add HTTP response header?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

How do I create a custom header in Django?

Note in Django you write the header name in capitals with underscores instead of dashes, but in the request on the client you must write it using dashes instead of underscores (production web servers will strip out custom headers with underscores in them for security reasons).

Can HTTP headers be repeated?

A sender MUST NOT generate multiple header fields with the same field name in a message unless either the entire field value for that header field is defined as a comma-separated list [i.e., #(values)] or the header field is a well-known exception (as noted below).


2 Answers

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',     ..., ] 
like image 73
Antoine Pinsard Avatar answered Sep 23 '22 02:09

Antoine Pinsard


When returning JsonResponse.

from django.http import JsonResponse  data = {'key','value'} # some data  response = JsonResponse(data,status=200)  response['Retry-after'] = 345 # seconds  response['custom-header'] = 'some value'  return response  
like image 40
Muhammad Faizan Fareed Avatar answered Sep 22 '22 02:09

Muhammad Faizan Fareed