Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access custom HTTP request headers on Django Rest Framework?

I'm sending a post request to my API made using django rest framework:

curl --header "X-MyHeader: 123" --data "test=test" http://127.0.0.1:8000/api/update_log/ 

In my rest framework view, I want to get my costum header, and if the custom header satisfies a condition, I will proceed to analyze my post data.

Ok, my view looks like:

class PostUpdateLogView(APIView):     throttle_classes = ()     permission_classes = ()     parser_classes = (         parsers.FormParser,         parsers.MultiPartParser,         parsers.JSONParser,     )        renderer_classes = (renderers.JSONRenderer,)      def post(self, request):         print request.Meta         # Get custom header         # Validate custom header         # Proceed to analize post data          # Make response         content = {             'response': 'response',         }          return Response(content) 

I'm trying to find my custom header on request.Meta element, but when I print request.Meta, I get a 500 error. If I print request.data, I get the expected response.

¿What is the way to get a custom header on my post request using django rest framework?

like image 392
Andrés Quiroga Avatar asked Feb 05 '15 13:02

Andrés Quiroga


People also ask

Can an HTTP request have custom headers?

Another example of using a custom HTTP header would be to implement the X-Pull header. You can use this custom header for a variety of purposes including rate limiting bandwidth on your origin server, restricting CDN traffic, creating custom logic on your origin server, etc.

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


1 Answers

The name of the meta data attribute of request is in upper case:

print request.META 

If your header is called "My-Header", your header will be available as:

request.META['HTTP_MY_HEADER'] 

Or:

request.META.get('HTTP_MY_HEADER') # return `None` if no such header 

Quote from the documentation:

HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

like image 107
catavaran Avatar answered Sep 20 '22 20:09

catavaran