diff options
author | Santiago Basulto <santiago.basulto@gmail.com> | 2018-05-04 20:37:01 -0300 |
---|---|---|
committer | Tim Graham <timograham@gmail.com> | 2019-01-16 13:38:47 -0500 |
commit | 4fc35a9c3efdc9154efce28cb23cb84f8834517e (patch) | |
tree | a4f7b10244cb933d827cf72ef57dc11e68c1a6ca /django/http/request.py | |
parent | aa5d0a5a90a690dc6f8fdbbffba143e32c86e40a (diff) | |
download | django-4fc35a9c3efdc9154efce28cb23cb84f8834517e.tar.gz |
Fixed #20147 -- Added HttpRequest.headers.
Diffstat (limited to 'django/http/request.py')
-rw-r--r-- | django/http/request.py | 30 |
1 files changed, 29 insertions, 1 deletions
diff --git a/django/http/request.py b/django/http/request.py index 7dc758d268..02a127d664 100644 --- a/django/http/request.py +++ b/django/http/request.py @@ -12,7 +12,9 @@ from django.core.exceptions import ( ) from django.core.files import uploadhandler from django.http.multipartparser import MultiPartParser, MultiPartParserError -from django.utils.datastructures import ImmutableList, MultiValueDict +from django.utils.datastructures import ( + CaseInsensitiveMapping, ImmutableList, MultiValueDict, +) from django.utils.deprecation import RemovedInDjango30Warning from django.utils.encoding import escape_uri_path, iri_to_uri from django.utils.functional import cached_property @@ -65,6 +67,10 @@ class HttpRequest: return '<%s>' % self.__class__.__name__ return '<%s: %s %r>' % (self.__class__.__name__, self.method, self.get_full_path()) + @cached_property + def headers(self): + return HttpHeaders(self.META) + def _get_raw_host(self): """ Return the HTTP host using the environment or request headers. Skip @@ -359,6 +365,28 @@ class HttpRequest: return list(self) +class HttpHeaders(CaseInsensitiveMapping): + HTTP_PREFIX = 'HTTP_' + # PEP 333 gives two headers which aren't prepended with HTTP_. + UNPREFIXED_HEADERS = {'CONTENT_TYPE', 'CONTENT_LENGTH'} + + def __init__(self, environ): + headers = {} + for header, value in environ.items(): + name = self.parse_header_name(header) + if name: + headers[name] = value + super().__init__(headers) + + @classmethod + def parse_header_name(cls, header): + if header.startswith(cls.HTTP_PREFIX): + header = header[len(cls.HTTP_PREFIX):] + elif header not in cls.UNPREFIXED_HEADERS: + return None + return header.replace('_', '-').title() + + class QueryDict(MultiValueDict): """ A specialized MultiValueDict which represents a query string. |