2019-06-13 16:11:41 +08:00
|
|
|
import cgi
|
|
|
|
import codecs
|
2012-10-22 02:12:59 +08:00
|
|
|
import copy
|
|
|
|
from io import BytesIO
|
2014-05-26 04:52:47 +08:00
|
|
|
from itertools import chain
|
2017-01-07 19:11:46 +08:00
|
|
|
from urllib.parse import quote, urlencode, urljoin, urlsplit
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
from django.conf import settings
|
|
|
|
from django.core import signing
|
2015-01-08 02:41:29 +08:00
|
|
|
from django.core.exceptions import (
|
|
|
|
DisallowedHost, ImproperlyConfigured, RequestDataTooBig,
|
|
|
|
)
|
2012-10-22 02:12:59 +08:00
|
|
|
from django.core.files import uploadhandler
|
2013-09-30 23:55:14 +08:00
|
|
|
from django.http.multipartparser import MultiPartParser, MultiPartParserError
|
2018-05-05 07:37:01 +08:00
|
|
|
from django.utils.datastructures import (
|
|
|
|
CaseInsensitiveMapping, ImmutableList, MultiValueDict,
|
|
|
|
)
|
2018-02-07 22:52:50 +08:00
|
|
|
from django.utils.encoding import escape_uri_path, iri_to_uri
|
2017-11-22 19:27:15 +08:00
|
|
|
from django.utils.functional import cached_property
|
2015-01-08 02:41:29 +08:00
|
|
|
from django.utils.http import is_same_domain, limited_parse_qsl
|
2019-10-26 22:42:32 +08:00
|
|
|
from django.utils.regex_helper import _lazy_re_compile
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
RAISE_ERROR = object()
|
2019-10-26 22:42:32 +08:00
|
|
|
host_validation_re = _lazy_re_compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:\d+)?$")
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
|
2019-01-28 23:01:35 +08:00
|
|
|
class UnreadablePostError(OSError):
|
2012-10-22 02:12:59 +08:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
2013-10-08 20:05:39 +08:00
|
|
|
class RawPostDataException(Exception):
|
|
|
|
"""
|
|
|
|
You cannot access raw_post_data from a request that has
|
|
|
|
multipart/* POST data if it has been accessed via POST,
|
|
|
|
FILES, etc..
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class HttpRequest:
|
2012-10-22 02:12:59 +08:00
|
|
|
"""A basic HTTP request."""
|
|
|
|
|
|
|
|
# The encoding used in GET/POST dicts. None means use default setting.
|
|
|
|
_encoding = None
|
|
|
|
_upload_handlers = []
|
|
|
|
|
|
|
|
def __init__(self):
|
2013-06-26 15:36:25 +08:00
|
|
|
# WARNING: The `WSGIRequest` subclass doesn't call `super`.
|
|
|
|
# Any variable assignment made here should also happen in
|
|
|
|
# `WSGIRequest.__init__()`.
|
|
|
|
|
Fixed #22799 -- Made GET and POST on HttpRequest QueryDicts, and FILES a MultiValueDict.
Previously, GET, POST, and FILES on an HttpRequest were created in
the __init__ method as dictionaries. This was not something you would
usually notice causing trouble in production as you'd only see a
WSGIRequest, but in testing using the test client, calling .getlist
on GET, POST, or FILES for a request with no get/post data resulted in
an AttributeError.
Changed GET and POST on an HttpRequest object to be mutable
QueryDicts (mutable because the Django tests, and probably many
third party tests, were expecting it).
2014-06-08 07:47:43 +08:00
|
|
|
self.GET = QueryDict(mutable=True)
|
|
|
|
self.POST = QueryDict(mutable=True)
|
|
|
|
self.COOKIES = {}
|
|
|
|
self.META = {}
|
|
|
|
self.FILES = MultiValueDict()
|
|
|
|
|
2012-10-22 02:12:59 +08:00
|
|
|
self.path = ''
|
|
|
|
self.path_info = ''
|
|
|
|
self.method = None
|
2013-03-11 06:24:34 +08:00
|
|
|
self.resolver_match = None
|
2015-08-07 13:51:39 +08:00
|
|
|
self.content_type = None
|
|
|
|
self.content_params = None
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
2014-11-20 17:28:16 +08:00
|
|
|
if self.method is None or not self.get_full_path():
|
2017-01-12 06:17:25 +08:00
|
|
|
return '<%s>' % self.__class__.__name__
|
|
|
|
return '<%s: %s %r>' % (self.__class__.__name__, self.method, self.get_full_path())
|
2012-10-22 02:12:59 +08:00
|
|
|
|
2018-05-05 07:37:01 +08:00
|
|
|
@cached_property
|
|
|
|
def headers(self):
|
|
|
|
return HttpHeaders(self.META)
|
|
|
|
|
2019-06-13 16:11:41 +08:00
|
|
|
def _set_content_type_params(self, meta):
|
|
|
|
"""Set content_type, content_params, and encoding."""
|
|
|
|
self.content_type, self.content_params = cgi.parse_header(meta.get('CONTENT_TYPE', ''))
|
|
|
|
if 'charset' in self.content_params:
|
|
|
|
try:
|
|
|
|
codecs.lookup(self.content_params['charset'])
|
|
|
|
except LookupError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
self.encoding = self.content_params['charset']
|
|
|
|
|
2015-09-04 02:52:49 +08:00
|
|
|
def _get_raw_host(self):
|
|
|
|
"""
|
|
|
|
Return the HTTP host using the environment or request headers. Skip
|
|
|
|
allowed hosts protection, so may return an insecure host.
|
|
|
|
"""
|
2012-10-22 02:12:59 +08:00
|
|
|
# We try three options, in order of decreasing preference.
|
|
|
|
if settings.USE_X_FORWARDED_HOST and (
|
2013-11-26 17:43:46 +08:00
|
|
|
'HTTP_X_FORWARDED_HOST' in self.META):
|
2012-10-22 02:12:59 +08:00
|
|
|
host = self.META['HTTP_X_FORWARDED_HOST']
|
|
|
|
elif 'HTTP_HOST' in self.META:
|
|
|
|
host = self.META['HTTP_HOST']
|
|
|
|
else:
|
|
|
|
# Reconstruct the host using the algorithm from PEP 333.
|
|
|
|
host = self.META['SERVER_NAME']
|
2015-08-03 07:56:54 +08:00
|
|
|
server_port = self.get_port()
|
2012-10-22 02:12:59 +08:00
|
|
|
if server_port != ('443' if self.is_secure() else '80'):
|
|
|
|
host = '%s:%s' % (host, server_port)
|
2015-09-04 02:52:49 +08:00
|
|
|
return host
|
|
|
|
|
|
|
|
def get_host(self):
|
|
|
|
"""Return the HTTP host using the environment or request headers."""
|
|
|
|
host = self._get_raw_host()
|
2012-10-22 02:12:59 +08:00
|
|
|
|
2016-10-18 00:14:49 +08:00
|
|
|
# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
|
|
|
|
allowed_hosts = settings.ALLOWED_HOSTS
|
|
|
|
if settings.DEBUG and not allowed_hosts:
|
2019-11-24 10:17:31 +08:00
|
|
|
allowed_hosts = ['.localhost', '127.0.0.1', '[::1]']
|
2013-03-28 00:37:08 +08:00
|
|
|
|
2013-04-04 04:27:20 +08:00
|
|
|
domain, port = split_domain_port(host)
|
2016-10-18 00:14:49 +08:00
|
|
|
if domain and validate_host(domain, allowed_hosts):
|
2013-02-10 01:17:01 +08:00
|
|
|
return host
|
|
|
|
else:
|
2013-04-04 04:27:20 +08:00
|
|
|
msg = "Invalid HTTP_HOST header: %r." % host
|
|
|
|
if domain:
|
2014-07-06 02:19:36 +08:00
|
|
|
msg += " You may need to add %r to ALLOWED_HOSTS." % domain
|
2013-03-28 00:37:08 +08:00
|
|
|
else:
|
2014-07-06 02:19:36 +08:00
|
|
|
msg += " The domain name provided is not valid according to RFC 1034/1035."
|
2013-05-16 07:14:28 +08:00
|
|
|
raise DisallowedHost(msg)
|
2012-10-22 02:12:59 +08:00
|
|
|
|
2015-08-03 07:56:54 +08:00
|
|
|
def get_port(self):
|
|
|
|
"""Return the port number for the request as a string."""
|
|
|
|
if settings.USE_X_FORWARDED_PORT and 'HTTP_X_FORWARDED_PORT' in self.META:
|
|
|
|
port = self.META['HTTP_X_FORWARDED_PORT']
|
|
|
|
else:
|
|
|
|
port = self.META['SERVER_PORT']
|
|
|
|
return str(port)
|
|
|
|
|
2015-03-23 03:04:31 +08:00
|
|
|
def get_full_path(self, force_append_slash=False):
|
2017-11-08 04:58:05 +08:00
|
|
|
return self._get_full_path(self.path, force_append_slash)
|
|
|
|
|
|
|
|
def get_full_path_info(self, force_append_slash=False):
|
|
|
|
return self._get_full_path(self.path_info, force_append_slash)
|
|
|
|
|
|
|
|
def _get_full_path(self, path, force_append_slash):
|
2012-10-22 02:12:59 +08:00
|
|
|
# RFC 3986 requires query string arguments to be in the ASCII range.
|
|
|
|
# Rather than crash if this doesn't happen, we encode defensively.
|
2015-03-23 03:04:31 +08:00
|
|
|
return '%s%s%s' % (
|
2017-11-08 04:58:05 +08:00
|
|
|
escape_uri_path(path),
|
|
|
|
'/' if force_append_slash and not path.endswith('/') else '',
|
2014-09-04 20:15:09 +08:00
|
|
|
('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else ''
|
|
|
|
)
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Attempt to return a signed cookie. If the signature fails or the
|
|
|
|
cookie has expired, raise an exception, unless the `default` argument
|
|
|
|
is provided, in which case return that value.
|
2012-10-22 02:12:59 +08:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
cookie_value = self.COOKIES[key]
|
|
|
|
except KeyError:
|
|
|
|
if default is not RAISE_ERROR:
|
|
|
|
return default
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
try:
|
|
|
|
value = signing.get_cookie_signer(salt=key + salt).unsign(
|
|
|
|
cookie_value, max_age=max_age)
|
|
|
|
except signing.BadSignature:
|
|
|
|
if default is not RAISE_ERROR:
|
|
|
|
return default
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
return value
|
|
|
|
|
2015-09-04 02:52:49 +08:00
|
|
|
def get_raw_uri(self):
|
|
|
|
"""
|
|
|
|
Return an absolute URI from variables available in this request. Skip
|
|
|
|
allowed hosts protection, so may return insecure URI.
|
|
|
|
"""
|
|
|
|
return '{scheme}://{host}{path}'.format(
|
|
|
|
scheme=self.scheme,
|
|
|
|
host=self._get_raw_host(),
|
|
|
|
path=self.get_full_path(),
|
|
|
|
)
|
|
|
|
|
2012-10-22 02:12:59 +08:00
|
|
|
def build_absolute_uri(self, location=None):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Build an absolute URI from the location and the variables available in
|
2018-07-16 16:48:20 +08:00
|
|
|
this request. If no ``location`` is specified, build the absolute URI
|
2017-01-25 05:23:56 +08:00
|
|
|
using request.get_full_path(). If the location is absolute, convert it
|
|
|
|
to an RFC 3987 compliant URI and return it. If location is relative or
|
|
|
|
is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
|
|
|
|
URL constructed from the request variables.
|
2012-10-22 02:12:59 +08:00
|
|
|
"""
|
2013-11-04 07:34:11 +08:00
|
|
|
if location is None:
|
|
|
|
# Make it an absolute url (but schemeless and domainless) for the
|
|
|
|
# edge case that the path starts with '//'.
|
|
|
|
location = '//%s' % self.get_full_path()
|
2019-12-23 18:34:36 +08:00
|
|
|
else:
|
|
|
|
# Coerce lazy locations.
|
|
|
|
location = str(location)
|
2013-11-04 07:34:11 +08:00
|
|
|
bits = urlsplit(location)
|
|
|
|
if not (bits.scheme and bits.netloc):
|
2017-11-22 19:27:15 +08:00
|
|
|
# Handle the simple, most common case. If the location is absolute
|
|
|
|
# and a scheme or host (netloc) isn't provided, skip an expensive
|
|
|
|
# urljoin() as long as no path segments are '.' or '..'.
|
|
|
|
if (bits.path.startswith('/') and not bits.scheme and not bits.netloc and
|
|
|
|
'/./' not in bits.path and '/../' not in bits.path):
|
|
|
|
# If location starts with '//' but has no netloc, reuse the
|
|
|
|
# schema and netloc from the current request. Strip the double
|
|
|
|
# slashes and continue as if it wasn't specified.
|
|
|
|
if location.startswith('//'):
|
|
|
|
location = location[2:]
|
|
|
|
location = self._current_scheme_host + location
|
|
|
|
else:
|
|
|
|
# Join the constructed URL with the provided location, which
|
|
|
|
# allows the provided location to apply query strings to the
|
|
|
|
# base path.
|
|
|
|
location = urljoin(self._current_scheme_host + self.path, location)
|
2012-10-22 02:12:59 +08:00
|
|
|
return iri_to_uri(location)
|
|
|
|
|
2017-11-22 19:27:15 +08:00
|
|
|
@cached_property
|
|
|
|
def _current_scheme_host(self):
|
|
|
|
return '{}://{}'.format(self.scheme, self.get_host())
|
|
|
|
|
2013-10-09 02:30:29 +08:00
|
|
|
def _get_scheme(self):
|
2015-03-11 00:22:55 +08:00
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Hook for subclasses like WSGIRequest to implement. Return 'http' by
|
2015-03-11 00:22:55 +08:00
|
|
|
default.
|
|
|
|
"""
|
|
|
|
return 'http'
|
2012-10-22 02:12:59 +08:00
|
|
|
|
2013-10-09 02:30:29 +08:00
|
|
|
@property
|
|
|
|
def scheme(self):
|
2012-10-22 02:12:59 +08:00
|
|
|
if settings.SECURE_PROXY_SSL_HEADER:
|
|
|
|
try:
|
2019-06-13 16:57:29 +08:00
|
|
|
header, secure_value = settings.SECURE_PROXY_SSL_HEADER
|
2012-10-22 02:12:59 +08:00
|
|
|
except ValueError:
|
2014-09-04 20:15:09 +08:00
|
|
|
raise ImproperlyConfigured(
|
|
|
|
'The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.'
|
|
|
|
)
|
2019-06-13 16:57:29 +08:00
|
|
|
header_value = self.META.get(header)
|
|
|
|
if header_value is not None:
|
|
|
|
return 'https' if header_value == secure_value else 'http'
|
2013-10-09 02:30:29 +08:00
|
|
|
return self._get_scheme()
|
|
|
|
|
|
|
|
def is_secure(self):
|
|
|
|
return self.scheme == 'https'
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def is_ajax(self):
|
|
|
|
return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
|
|
|
|
|
|
|
|
@property
|
|
|
|
def encoding(self):
|
|
|
|
return self._encoding
|
|
|
|
|
|
|
|
@encoding.setter
|
|
|
|
def encoding(self, val):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Set the encoding used for GET/POST accesses. If the GET or POST
|
|
|
|
dictionary has already been created, remove and recreate it on the
|
2012-10-22 02:12:59 +08:00
|
|
|
next access (so that it is decoded correctly).
|
|
|
|
"""
|
|
|
|
self._encoding = val
|
2016-11-18 01:46:42 +08:00
|
|
|
if hasattr(self, 'GET'):
|
|
|
|
del self.GET
|
2012-10-22 02:12:59 +08:00
|
|
|
if hasattr(self, '_post'):
|
|
|
|
del self._post
|
|
|
|
|
|
|
|
def _initialize_handlers(self):
|
|
|
|
self._upload_handlers = [uploadhandler.load_handler(handler, self)
|
|
|
|
for handler in settings.FILE_UPLOAD_HANDLERS]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def upload_handlers(self):
|
|
|
|
if not self._upload_handlers:
|
|
|
|
# If there are no upload handlers defined, initialize them from settings.
|
|
|
|
self._initialize_handlers()
|
|
|
|
return self._upload_handlers
|
|
|
|
|
|
|
|
@upload_handlers.setter
|
|
|
|
def upload_handlers(self, upload_handlers):
|
|
|
|
if hasattr(self, '_files'):
|
|
|
|
raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
|
|
|
|
self._upload_handlers = upload_handlers
|
|
|
|
|
|
|
|
def parse_file_upload(self, META, post_data):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return a tuple of (POST QueryDict, FILES MultiValueDict)."""
|
2012-10-22 02:12:59 +08:00
|
|
|
self.upload_handlers = ImmutableList(
|
|
|
|
self.upload_handlers,
|
|
|
|
warning="You cannot alter upload handlers after the upload has been processed."
|
|
|
|
)
|
|
|
|
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
|
|
|
|
return parser.parse()
|
|
|
|
|
|
|
|
@property
|
|
|
|
def body(self):
|
|
|
|
if not hasattr(self, '_body'):
|
|
|
|
if self._read_started:
|
2013-10-08 20:05:39 +08:00
|
|
|
raise RawPostDataException("You cannot access body after reading from request's data stream")
|
2015-01-08 02:41:29 +08:00
|
|
|
|
|
|
|
# Limit the maximum request data size that will be handled in-memory.
|
|
|
|
if (settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and
|
2016-08-04 00:46:57 +08:00
|
|
|
int(self.META.get('CONTENT_LENGTH') or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE):
|
2015-01-08 02:41:29 +08:00
|
|
|
raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.')
|
|
|
|
|
2012-10-22 02:12:59 +08:00
|
|
|
try:
|
|
|
|
self._body = self.read()
|
2019-01-28 23:01:35 +08:00
|
|
|
except OSError as e:
|
2017-01-08 03:13:29 +08:00
|
|
|
raise UnreadablePostError(*e.args) from e
|
2012-10-22 02:12:59 +08:00
|
|
|
self._stream = BytesIO(self._body)
|
|
|
|
return self._body
|
|
|
|
|
|
|
|
def _mark_post_parse_error(self):
|
2016-05-04 00:04:08 +08:00
|
|
|
self._post = QueryDict()
|
2012-10-22 02:12:59 +08:00
|
|
|
self._files = MultiValueDict()
|
|
|
|
|
|
|
|
def _load_post_and_files(self):
|
|
|
|
"""Populate self._post and self._files if the content-type is a form type"""
|
|
|
|
if self.method != 'POST':
|
2016-05-04 00:04:08 +08:00
|
|
|
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
|
2012-10-22 02:12:59 +08:00
|
|
|
return
|
|
|
|
if self._read_started and not hasattr(self, '_body'):
|
|
|
|
self._mark_post_parse_error()
|
|
|
|
return
|
|
|
|
|
2015-08-07 13:51:39 +08:00
|
|
|
if self.content_type == 'multipart/form-data':
|
2012-10-22 02:12:59 +08:00
|
|
|
if hasattr(self, '_body'):
|
|
|
|
# Use already read data
|
|
|
|
data = BytesIO(self._body)
|
|
|
|
else:
|
|
|
|
data = self
|
|
|
|
try:
|
|
|
|
self._post, self._files = self.parse_file_upload(self.META, data)
|
2013-09-30 23:55:14 +08:00
|
|
|
except MultiPartParserError:
|
2014-04-27 01:18:45 +08:00
|
|
|
# An error occurred while parsing POST data. Since when
|
2012-10-22 02:12:59 +08:00
|
|
|
# formatting the error the request handler might access
|
|
|
|
# self.POST, set self._post and self._file to prevent
|
|
|
|
# attempts to parse POST data again.
|
2013-11-16 07:54:20 +08:00
|
|
|
self._mark_post_parse_error()
|
2012-10-22 02:12:59 +08:00
|
|
|
raise
|
2015-08-07 13:51:39 +08:00
|
|
|
elif self.content_type == 'application/x-www-form-urlencoded':
|
2012-10-22 02:12:59 +08:00
|
|
|
self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
|
|
|
|
else:
|
2016-05-04 00:04:08 +08:00
|
|
|
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
|
2012-10-22 02:12:59 +08:00
|
|
|
|
2014-05-26 04:52:47 +08:00
|
|
|
def close(self):
|
|
|
|
if hasattr(self, '_files'):
|
|
|
|
for f in chain.from_iterable(l[1] for l in self._files.lists()):
|
|
|
|
f.close()
|
|
|
|
|
2013-11-03 05:02:56 +08:00
|
|
|
# File-like and iterator interface.
|
|
|
|
#
|
|
|
|
# Expects self._stream to be set to an appropriate source of bytes by
|
|
|
|
# a corresponding request subclass (e.g. WSGIRequest).
|
|
|
|
# Also when request data has already been read by request.POST or
|
|
|
|
# request.body, self._stream points to a BytesIO instance
|
|
|
|
# containing that data.
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def read(self, *args, **kwargs):
|
|
|
|
self._read_started = True
|
2013-06-01 16:26:46 +08:00
|
|
|
try:
|
|
|
|
return self._stream.read(*args, **kwargs)
|
2019-01-28 23:01:35 +08:00
|
|
|
except OSError as e:
|
2017-01-08 03:13:29 +08:00
|
|
|
raise UnreadablePostError(*e.args) from e
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def readline(self, *args, **kwargs):
|
|
|
|
self._read_started = True
|
2013-06-01 16:26:46 +08:00
|
|
|
try:
|
|
|
|
return self._stream.readline(*args, **kwargs)
|
2019-01-28 23:01:35 +08:00
|
|
|
except OSError as e:
|
2017-01-08 03:13:29 +08:00
|
|
|
raise UnreadablePostError(*e.args) from e
|
2012-10-22 02:12:59 +08:00
|
|
|
|
2017-04-27 02:17:41 +08:00
|
|
|
def __iter__(self):
|
2018-07-10 21:13:36 +08:00
|
|
|
return iter(self.readline, b'')
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def readlines(self):
|
2017-08-24 04:48:29 +08:00
|
|
|
return list(self)
|
2018-05-05 07:37:01 +08:00
|
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
2019-05-09 22:26:52 +08:00
|
|
|
def __getitem__(self, key):
|
|
|
|
"""Allow header lookup using underscores in place of hyphens."""
|
|
|
|
return super().__getitem__(key.replace('_', '-'))
|
|
|
|
|
2018-05-05 07:37:01 +08:00
|
|
|
@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()
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
|
|
|
|
class QueryDict(MultiValueDict):
|
|
|
|
"""
|
2014-06-12 04:41:25 +08:00
|
|
|
A specialized MultiValueDict which represents a query string.
|
2012-10-22 02:12:59 +08:00
|
|
|
|
2014-06-12 04:41:25 +08:00
|
|
|
A QueryDict can be used to represent GET or POST data. It subclasses
|
|
|
|
MultiValueDict since keys in such data can be repeated, for instance
|
|
|
|
in the data from a form with a <select multiple> field.
|
|
|
|
|
|
|
|
By default QueryDicts are immutable, though the copy() method
|
|
|
|
will always return a mutable copy.
|
|
|
|
|
|
|
|
Both keys and values set on this class are converted from the given encoding
|
2017-01-21 05:04:05 +08:00
|
|
|
(DEFAULT_CHARSET by default) to str.
|
2012-10-22 02:12:59 +08:00
|
|
|
"""
|
2014-06-12 04:41:25 +08:00
|
|
|
|
2012-10-22 02:12:59 +08:00
|
|
|
# These are both reset in __init__, but is specified here at the class
|
|
|
|
# level so that unpickling will have valid values
|
|
|
|
_mutable = True
|
|
|
|
_encoding = None
|
|
|
|
|
2014-06-25 10:01:39 +08:00
|
|
|
def __init__(self, query_string=None, mutable=False, encoding=None):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__()
|
2018-01-04 07:52:12 +08:00
|
|
|
self.encoding = encoding or settings.DEFAULT_CHARSET
|
2015-01-08 02:41:29 +08:00
|
|
|
query_string = query_string or ''
|
|
|
|
parse_qsl_kwargs = {
|
|
|
|
'keep_blank_values': True,
|
|
|
|
'fields_limit': settings.DATA_UPLOAD_MAX_NUMBER_FIELDS,
|
2018-01-04 07:52:12 +08:00
|
|
|
'encoding': self.encoding,
|
2015-01-08 02:41:29 +08:00
|
|
|
}
|
2016-12-01 18:38:01 +08:00
|
|
|
if isinstance(query_string, bytes):
|
|
|
|
# query_string normally contains URL-encoded data, a subset of ASCII.
|
|
|
|
try:
|
2018-01-04 07:52:12 +08:00
|
|
|
query_string = query_string.decode(self.encoding)
|
2016-12-01 18:38:01 +08:00
|
|
|
except UnicodeDecodeError:
|
|
|
|
# ... but some user agents are misbehaving :-(
|
|
|
|
query_string = query_string.decode('iso-8859-1')
|
|
|
|
for key, value in limited_parse_qsl(query_string, **parse_qsl_kwargs):
|
|
|
|
self.appendlist(key, value)
|
2012-10-22 02:12:59 +08:00
|
|
|
self._mutable = mutable
|
|
|
|
|
2016-06-04 06:50:38 +08:00
|
|
|
@classmethod
|
|
|
|
def fromkeys(cls, iterable, value='', mutable=False, encoding=None):
|
|
|
|
"""
|
|
|
|
Return a new QueryDict with keys (may be repeated) from an iterable and
|
|
|
|
values from value.
|
|
|
|
"""
|
|
|
|
q = cls('', mutable=True, encoding=encoding)
|
|
|
|
for key in iterable:
|
|
|
|
q.appendlist(key, value)
|
|
|
|
if not mutable:
|
|
|
|
q._mutable = False
|
|
|
|
return q
|
|
|
|
|
2012-10-22 02:12:59 +08:00
|
|
|
@property
|
|
|
|
def encoding(self):
|
|
|
|
if self._encoding is None:
|
|
|
|
self._encoding = settings.DEFAULT_CHARSET
|
|
|
|
return self._encoding
|
|
|
|
|
|
|
|
@encoding.setter
|
|
|
|
def encoding(self, value):
|
|
|
|
self._encoding = value
|
|
|
|
|
|
|
|
def _assert_mutable(self):
|
|
|
|
if not self._mutable:
|
|
|
|
raise AttributeError("This QueryDict instance is immutable")
|
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
|
|
|
self._assert_mutable()
|
|
|
|
key = bytes_to_text(key, self.encoding)
|
|
|
|
value = bytes_to_text(value, self.encoding)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__setitem__(key, value)
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def __delitem__(self, key):
|
|
|
|
self._assert_mutable()
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__delitem__(key)
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def __copy__(self):
|
|
|
|
result = self.__class__('', mutable=True, encoding=self.encoding)
|
2017-01-07 19:11:46 +08:00
|
|
|
for key, value in self.lists():
|
2012-10-22 02:12:59 +08:00
|
|
|
result.setlist(key, value)
|
|
|
|
return result
|
|
|
|
|
|
|
|
def __deepcopy__(self, memo):
|
|
|
|
result = self.__class__('', mutable=True, encoding=self.encoding)
|
|
|
|
memo[id(self)] = result
|
2017-01-07 19:11:46 +08:00
|
|
|
for key, value in self.lists():
|
2012-10-22 02:12:59 +08:00
|
|
|
result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo))
|
|
|
|
return result
|
|
|
|
|
|
|
|
def setlist(self, key, list_):
|
|
|
|
self._assert_mutable()
|
|
|
|
key = bytes_to_text(key, self.encoding)
|
|
|
|
list_ = [bytes_to_text(elt, self.encoding) for elt in list_]
|
2017-01-21 21:13:44 +08:00
|
|
|
super().setlist(key, list_)
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def setlistdefault(self, key, default_list=None):
|
|
|
|
self._assert_mutable()
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().setlistdefault(key, default_list)
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def appendlist(self, key, value):
|
|
|
|
self._assert_mutable()
|
|
|
|
key = bytes_to_text(key, self.encoding)
|
|
|
|
value = bytes_to_text(value, self.encoding)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().appendlist(key, value)
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def pop(self, key, *args):
|
|
|
|
self._assert_mutable()
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().pop(key, *args)
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def popitem(self):
|
|
|
|
self._assert_mutable()
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().popitem()
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
self._assert_mutable()
|
2017-01-21 21:13:44 +08:00
|
|
|
super().clear()
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def setdefault(self, key, default=None):
|
|
|
|
self._assert_mutable()
|
|
|
|
key = bytes_to_text(key, self.encoding)
|
|
|
|
default = bytes_to_text(default, self.encoding)
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().setdefault(key, default)
|
2012-10-22 02:12:59 +08:00
|
|
|
|
|
|
|
def copy(self):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return a mutable copy of this object."""
|
2012-10-22 02:12:59 +08:00
|
|
|
return self.__deepcopy__({})
|
|
|
|
|
|
|
|
def urlencode(self, safe=None):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return an encoded string of all query string arguments.
|
2012-10-22 02:12:59 +08:00
|
|
|
|
2017-01-25 05:23:56 +08:00
|
|
|
`safe` specifies characters which don't require quoting, for example::
|
2012-10-22 02:12:59 +08:00
|
|
|
|
2017-01-25 05:23:56 +08:00
|
|
|
>>> q = QueryDict(mutable=True)
|
|
|
|
>>> q['next'] = '/a&b/'
|
|
|
|
>>> q.urlencode()
|
|
|
|
'next=%2Fa%26b%2F'
|
|
|
|
>>> q.urlencode(safe='/')
|
|
|
|
'next=/a%26b/'
|
2012-10-22 02:12:59 +08:00
|
|
|
"""
|
|
|
|
output = []
|
|
|
|
if safe:
|
2018-02-07 22:52:50 +08:00
|
|
|
safe = safe.encode(self.encoding)
|
2016-01-24 00:47:07 +08:00
|
|
|
|
|
|
|
def encode(k, v):
|
|
|
|
return '%s=%s' % ((quote(k, safe), quote(v, safe)))
|
2012-10-22 02:12:59 +08:00
|
|
|
else:
|
2016-01-24 00:47:07 +08:00
|
|
|
def encode(k, v):
|
|
|
|
return urlencode({k: v})
|
2012-10-22 02:12:59 +08:00
|
|
|
for k, list_ in self.lists():
|
2018-02-07 22:52:50 +08:00
|
|
|
output.extend(
|
2018-08-03 09:56:26 +08:00
|
|
|
encode(k.encode(self.encoding), str(v).encode(self.encoding))
|
2018-02-07 22:52:50 +08:00
|
|
|
for v in list_
|
|
|
|
)
|
2012-10-22 02:12:59 +08:00
|
|
|
return '&'.join(output)
|
|
|
|
|
|
|
|
|
|
|
|
# It's neither necessary nor appropriate to use
|
2017-01-26 17:08:08 +08:00
|
|
|
# django.utils.encoding.force_str() for parsing URLs and form inputs. Thus,
|
2012-10-22 02:12:59 +08:00
|
|
|
# this slightly more restricted function, used by QueryDict.
|
|
|
|
def bytes_to_text(s, encoding):
|
|
|
|
"""
|
2017-01-20 17:20:53 +08:00
|
|
|
Convert bytes objects to strings, using the given encoding. Illegally
|
2012-10-22 02:12:59 +08:00
|
|
|
encoded input characters are replaced with Unicode "unknown" codepoint
|
|
|
|
(\ufffd).
|
|
|
|
|
2017-01-20 17:20:53 +08:00
|
|
|
Return any non-bytes objects without change.
|
2012-10-22 02:12:59 +08:00
|
|
|
"""
|
|
|
|
if isinstance(s, bytes):
|
2016-12-29 23:27:49 +08:00
|
|
|
return str(s, encoding, 'replace')
|
2012-10-22 02:12:59 +08:00
|
|
|
else:
|
|
|
|
return s
|
2013-02-10 01:17:01 +08:00
|
|
|
|
|
|
|
|
2013-04-04 04:27:20 +08:00
|
|
|
def split_domain_port(host):
|
|
|
|
"""
|
|
|
|
Return a (domain, port) tuple from a given host.
|
|
|
|
|
2018-09-25 22:30:18 +08:00
|
|
|
Returned domain is lowercased. If the host is invalid, the domain will be
|
2013-04-04 04:27:20 +08:00
|
|
|
empty.
|
|
|
|
"""
|
|
|
|
host = host.lower()
|
|
|
|
|
|
|
|
if not host_validation_re.match(host):
|
|
|
|
return '', ''
|
|
|
|
|
|
|
|
if host[-1] == ']':
|
|
|
|
# It's an IPv6 address without a port.
|
|
|
|
return host, ''
|
|
|
|
bits = host.rsplit(':', 1)
|
2016-11-30 07:17:10 +08:00
|
|
|
domain, port = bits if len(bits) == 2 else (bits[0], '')
|
|
|
|
# Remove a trailing dot (if present) from the domain.
|
|
|
|
domain = domain[:-1] if domain.endswith('.') else domain
|
|
|
|
return domain, port
|
2013-04-04 04:27:20 +08:00
|
|
|
|
|
|
|
|
2013-02-10 01:17:01 +08:00
|
|
|
def validate_host(host, allowed_hosts):
|
|
|
|
"""
|
2013-04-04 04:27:20 +08:00
|
|
|
Validate the given host for this site.
|
2013-02-10 01:17:01 +08:00
|
|
|
|
|
|
|
Check that the host looks valid and matches a host or host pattern in the
|
|
|
|
given list of ``allowed_hosts``. Any pattern beginning with a period
|
|
|
|
matches a domain and all its subdomains (e.g. ``.example.com`` matches
|
|
|
|
``example.com`` and any subdomain), ``*`` matches anything, and anything
|
|
|
|
else must match exactly.
|
|
|
|
|
2018-09-25 22:30:18 +08:00
|
|
|
Note: This function assumes that the given host is lowercased and has
|
2013-04-04 04:27:20 +08:00
|
|
|
already had the port, if any, stripped off.
|
|
|
|
|
2013-02-10 01:17:01 +08:00
|
|
|
Return ``True`` for a valid host, ``False`` otherwise.
|
|
|
|
"""
|
2017-12-27 02:44:12 +08:00
|
|
|
return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts)
|