How can I get all the request headers in Django?

前端 未结 9 2490
误落风尘
误落风尘 2020-11-29 20:57

I need to get all the Django request headers. From what i\'ve read, Django simply dumps everything into the request.META variable along with a lot aof other dat

9条回答
  •  抹茶落季
    2020-11-29 21:19

    This is another way to do it, very similar to Manoj Govindan's answer above:

    import re
    regex_http_          = re.compile(r'^HTTP_.+$')
    regex_content_type   = re.compile(r'^CONTENT_TYPE$')
    regex_content_length = re.compile(r'^CONTENT_LENGTH$')
    
    request_headers = {}
    for header in request.META:
        if regex_http_.match(header) or regex_content_type.match(header) or regex_content_length.match(header):
            request_headers[header] = request.META[header]
    

    That will also grab the CONTENT_TYPE and CONTENT_LENGTH request headers, along with the HTTP_ ones. request_headers['some_key] == request.META['some_key'].

    Modify accordingly if you need to include/omit certain headers. Django lists a bunch, but not all, of them here: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META

    Django's algorithm for request headers:

    1. Replace hyphen - with underscore _
    2. Convert to UPPERCASE.
    3. Prepend HTTP_ to all headers in original request, except for CONTENT_TYPE and CONTENT_LENGTH.

    The values of each header should be unmodified.

提交回复
热议问题