request.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. import codecs
  2. import copy
  3. import operator
  4. import os
  5. from io import BytesIO
  6. from itertools import chain
  7. from urllib.parse import parse_qsl, quote, urlencode, urljoin, urlsplit
  8. from django.conf import settings
  9. from django.core import signing
  10. from django.core.exceptions import (
  11. BadRequest,
  12. DisallowedHost,
  13. ImproperlyConfigured,
  14. RequestDataTooBig,
  15. TooManyFieldsSent,
  16. )
  17. from django.core.files import uploadhandler
  18. from django.http.multipartparser import (
  19. MultiPartParser,
  20. MultiPartParserError,
  21. TooManyFilesSent,
  22. )
  23. from django.utils.datastructures import (
  24. CaseInsensitiveMapping,
  25. ImmutableList,
  26. MultiValueDict,
  27. )
  28. from django.utils.encoding import escape_uri_path, iri_to_uri
  29. from django.utils.functional import cached_property
  30. from django.utils.http import is_same_domain, parse_header_parameters
  31. from django.utils.regex_helper import _lazy_re_compile
  32. RAISE_ERROR = object()
  33. host_validation_re = _lazy_re_compile(
  34. r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9.:]+\])(?::([0-9]+))?$"
  35. )
  36. class UnreadablePostError(OSError):
  37. pass
  38. class RawPostDataException(Exception):
  39. """
  40. You cannot access raw_post_data from a request that has
  41. multipart/* POST data if it has been accessed via POST,
  42. FILES, etc..
  43. """
  44. pass
  45. class HttpRequest:
  46. """A basic HTTP request."""
  47. # The encoding used in GET/POST dicts. None means use default setting.
  48. _encoding = None
  49. _upload_handlers = []
  50. _multipart_parser_class = MultiPartParser
  51. def __init__(self):
  52. # WARNING: The `WSGIRequest` subclass doesn't call `super`.
  53. # Any variable assignment made here should also happen in
  54. # `WSGIRequest.__init__()`.
  55. self.GET = QueryDict(mutable=True)
  56. self.POST = QueryDict(mutable=True)
  57. self.COOKIES = {}
  58. self.META = {}
  59. self.FILES = MultiValueDict()
  60. self.path = ""
  61. self.path_info = ""
  62. self.method = None
  63. self.resolver_match = None
  64. self.content_type = None
  65. self.content_params = None
  66. def __repr__(self):
  67. if self.method is None or not self.get_full_path():
  68. return "<%s>" % self.__class__.__name__
  69. return "<%s: %s %r>" % (
  70. self.__class__.__name__,
  71. self.method,
  72. self.get_full_path(),
  73. )
  74. @cached_property
  75. def headers(self):
  76. return HttpHeaders(self.META)
  77. @cached_property
  78. def accepted_types(self):
  79. """
  80. Return a list of MediaType instances, in order of preference (quality).
  81. """
  82. header_value = self.headers.get("Accept", "*/*")
  83. return sorted(
  84. (
  85. media_type
  86. for token in header_value.split(",")
  87. if token.strip() and (media_type := MediaType(token)).quality != 0
  88. ),
  89. key=operator.attrgetter("quality", "specificity"),
  90. reverse=True,
  91. )
  92. @cached_property
  93. def accepted_types_by_precedence(self):
  94. """
  95. Return a list of MediaType instances, in order of precedence
  96. (specificity).
  97. """
  98. return sorted(
  99. self.accepted_types,
  100. key=operator.attrgetter("specificity", "quality"),
  101. reverse=True,
  102. )
  103. def accepted_type(self, media_type):
  104. """
  105. Return the MediaType instance which best matches the given media type.
  106. """
  107. media_type = MediaType(media_type)
  108. return next(
  109. (
  110. accepted_type
  111. for accepted_type in self.accepted_types_by_precedence
  112. if media_type.match(accepted_type)
  113. ),
  114. None,
  115. )
  116. def get_preferred_type(self, media_types):
  117. """Select the preferred media type from the provided options."""
  118. if not media_types or not self.accepted_types:
  119. return None
  120. desired_types = [
  121. (accepted_type, media_type)
  122. for media_type in media_types
  123. if (accepted_type := self.accepted_type(media_type)) is not None
  124. ]
  125. if not desired_types:
  126. return None
  127. # Of the desired media types, select the one which is preferred.
  128. return min(desired_types, key=lambda t: self.accepted_types.index(t[0]))[1]
  129. def accepts(self, media_type):
  130. """Does the client accept a response in the given media type?"""
  131. return self.accepted_type(media_type) is not None
  132. def _set_content_type_params(self, meta):
  133. """Set content_type, content_params, and encoding."""
  134. try:
  135. self.content_type, self.content_params = parse_header_parameters(
  136. meta.get("CONTENT_TYPE", "")
  137. )
  138. except ValueError as exc:
  139. raise BadRequest("Invalid Content-Type header.") from exc
  140. if "charset" in self.content_params:
  141. try:
  142. codecs.lookup(self.content_params["charset"])
  143. except LookupError:
  144. pass
  145. else:
  146. self.encoding = self.content_params["charset"]
  147. def _get_raw_host(self):
  148. """
  149. Return the HTTP host using the environment or request headers. Skip
  150. allowed hosts protection, so may return an insecure host.
  151. """
  152. # We try three options, in order of decreasing preference.
  153. if settings.USE_X_FORWARDED_HOST and ("HTTP_X_FORWARDED_HOST" in self.META):
  154. host = self.META["HTTP_X_FORWARDED_HOST"]
  155. elif "HTTP_HOST" in self.META:
  156. host = self.META["HTTP_HOST"]
  157. else:
  158. # Reconstruct the host using the algorithm from PEP 333.
  159. host = self.META["SERVER_NAME"]
  160. server_port = self.get_port()
  161. if server_port != ("443" if self.is_secure() else "80"):
  162. host = "%s:%s" % (host, server_port)
  163. return host
  164. def get_host(self):
  165. """Return the HTTP host using the environment or request headers."""
  166. host = self._get_raw_host()
  167. # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
  168. allowed_hosts = settings.ALLOWED_HOSTS
  169. if settings.DEBUG and not allowed_hosts:
  170. allowed_hosts = [".localhost", "127.0.0.1", "[::1]"]
  171. domain, port = split_domain_port(host)
  172. if domain and validate_host(domain, allowed_hosts):
  173. return host
  174. else:
  175. msg = "Invalid HTTP_HOST header: %r." % host
  176. if domain:
  177. msg += " You may need to add %r to ALLOWED_HOSTS." % domain
  178. else:
  179. msg += (
  180. " The domain name provided is not valid according to RFC 1034/1035."
  181. )
  182. raise DisallowedHost(msg)
  183. def get_port(self):
  184. """Return the port number for the request as a string."""
  185. if settings.USE_X_FORWARDED_PORT and "HTTP_X_FORWARDED_PORT" in self.META:
  186. port = self.META["HTTP_X_FORWARDED_PORT"]
  187. else:
  188. port = self.META["SERVER_PORT"]
  189. return str(port)
  190. def get_full_path(self, force_append_slash=False):
  191. return self._get_full_path(self.path, force_append_slash)
  192. def get_full_path_info(self, force_append_slash=False):
  193. return self._get_full_path(self.path_info, force_append_slash)
  194. def _get_full_path(self, path, force_append_slash):
  195. # RFC 3986 requires query string arguments to be in the ASCII range.
  196. # Rather than crash if this doesn't happen, we encode defensively.
  197. return "%s%s%s" % (
  198. escape_uri_path(path),
  199. "/" if force_append_slash and not path.endswith("/") else "",
  200. (
  201. ("?" + iri_to_uri(self.META.get("QUERY_STRING", "")))
  202. if self.META.get("QUERY_STRING", "")
  203. else ""
  204. ),
  205. )
  206. def get_signed_cookie(self, key, default=RAISE_ERROR, salt="", max_age=None):
  207. """
  208. Attempt to return a signed cookie. If the signature fails or the
  209. cookie has expired, raise an exception, unless the `default` argument
  210. is provided, in which case return that value.
  211. """
  212. try:
  213. cookie_value = self.COOKIES[key]
  214. except KeyError:
  215. if default is not RAISE_ERROR:
  216. return default
  217. else:
  218. raise
  219. try:
  220. value = signing._unsign_cookie(
  221. cookie_value, cookie_name=key, salt=salt, max_age=max_age
  222. )
  223. except signing.BadSignature:
  224. if default is not RAISE_ERROR:
  225. return default
  226. else:
  227. raise
  228. return value
  229. def build_absolute_uri(self, location=None):
  230. """
  231. Build an absolute URI from the location and the variables available in
  232. this request. If no ``location`` is specified, build the absolute URI
  233. using request.get_full_path(). If the location is absolute, convert it
  234. to an RFC 3987 compliant URI and return it. If location is relative or
  235. is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
  236. URL constructed from the request variables.
  237. """
  238. if location is None:
  239. # Make it an absolute url (but schemeless and domainless) for the
  240. # edge case that the path starts with '//'.
  241. location = "//%s" % self.get_full_path()
  242. else:
  243. # Coerce lazy locations.
  244. location = str(location)
  245. bits = urlsplit(location)
  246. if not (bits.scheme and bits.netloc):
  247. # Handle the simple, most common case. If the location is absolute
  248. # and a scheme or host (netloc) isn't provided, skip an expensive
  249. # urljoin() as long as no path segments are '.' or '..'.
  250. if (
  251. bits.path.startswith("/")
  252. and not bits.scheme
  253. and not bits.netloc
  254. and "/./" not in bits.path
  255. and "/../" not in bits.path
  256. ):
  257. # If location starts with '//' but has no netloc, reuse the
  258. # schema and netloc from the current request. Strip the double
  259. # slashes and continue as if it wasn't specified.
  260. location = self._current_scheme_host + location.removeprefix("//")
  261. else:
  262. # Join the constructed URL with the provided location, which
  263. # allows the provided location to apply query strings to the
  264. # base path.
  265. location = urljoin(self._current_scheme_host + self.path, location)
  266. return iri_to_uri(location)
  267. @cached_property
  268. def _current_scheme_host(self):
  269. return "{}://{}".format(self.scheme, self.get_host())
  270. def _get_scheme(self):
  271. """
  272. Hook for subclasses like WSGIRequest to implement. Return 'http' by
  273. default.
  274. """
  275. return "http"
  276. @property
  277. def scheme(self):
  278. if settings.SECURE_PROXY_SSL_HEADER:
  279. try:
  280. header, secure_value = settings.SECURE_PROXY_SSL_HEADER
  281. except ValueError:
  282. raise ImproperlyConfigured(
  283. "The SECURE_PROXY_SSL_HEADER setting must be a tuple containing "
  284. "two values."
  285. )
  286. header_value = self.META.get(header)
  287. if header_value is not None:
  288. header_value, *_ = header_value.split(",", 1)
  289. return "https" if header_value.strip() == secure_value else "http"
  290. return self._get_scheme()
  291. def is_secure(self):
  292. return self.scheme == "https"
  293. @property
  294. def encoding(self):
  295. return self._encoding
  296. @encoding.setter
  297. def encoding(self, val):
  298. """
  299. Set the encoding used for GET/POST accesses. If the GET or POST
  300. dictionary has already been created, remove and recreate it on the
  301. next access (so that it is decoded correctly).
  302. """
  303. self._encoding = val
  304. if hasattr(self, "GET"):
  305. del self.GET
  306. if hasattr(self, "_post"):
  307. del self._post
  308. def _initialize_handlers(self):
  309. self._upload_handlers = [
  310. uploadhandler.load_handler(handler, self)
  311. for handler in settings.FILE_UPLOAD_HANDLERS
  312. ]
  313. @property
  314. def upload_handlers(self):
  315. if not self._upload_handlers:
  316. # If there are no upload handlers defined, initialize them from
  317. # settings.
  318. self._initialize_handlers()
  319. return self._upload_handlers
  320. @upload_handlers.setter
  321. def upload_handlers(self, upload_handlers):
  322. if hasattr(self, "_files"):
  323. raise AttributeError(
  324. "You cannot set the upload handlers after the upload has been "
  325. "processed."
  326. )
  327. self._upload_handlers = upload_handlers
  328. @property
  329. def multipart_parser_class(self):
  330. return self._multipart_parser_class
  331. @multipart_parser_class.setter
  332. def multipart_parser_class(self, multipart_parser_class):
  333. if hasattr(self, "_files"):
  334. raise RuntimeError(
  335. "You cannot set the multipart parser class after the upload has been "
  336. "processed."
  337. )
  338. self._multipart_parser_class = multipart_parser_class
  339. def parse_file_upload(self, META, post_data):
  340. """Return a tuple of (POST QueryDict, FILES MultiValueDict)."""
  341. self.upload_handlers = ImmutableList(
  342. self.upload_handlers,
  343. warning=(
  344. "You cannot alter upload handlers after the upload has been "
  345. "processed."
  346. ),
  347. )
  348. parser = self.multipart_parser_class(
  349. META, post_data, self.upload_handlers, self.encoding
  350. )
  351. return parser.parse()
  352. @property
  353. def body(self):
  354. if not hasattr(self, "_body"):
  355. if self._read_started:
  356. raise RawPostDataException(
  357. "You cannot access body after reading from request's data stream"
  358. )
  359. # Make Content-Length fall back to 0 if malformed (e.g. ASGIRequest
  360. # comma-joins duplicate Content-Length headers).
  361. try:
  362. content_length = int(self.META.get("CONTENT_LENGTH") or 0)
  363. except (ValueError, TypeError):
  364. content_length = 0
  365. # Limit the maximum request data size that will be handled
  366. # in-memory. Reject early when Content-Length is present and
  367. # already exceeds the limit, avoiding reading the body at all.
  368. self._check_data_too_big(content_length)
  369. # Content-Length can be absent or understated (e.g.
  370. # `Transfer-Encoding: chunked` on ASGI), so for seekable
  371. # streams (e.g. SpooledTemporaryFile on ASGI), check the actual
  372. # buffered size before reading it all into memory.
  373. if self._stream.seekable():
  374. stream_size = self._stream.seek(0, os.SEEK_END)
  375. self._check_data_too_big(stream_size)
  376. self._stream.seek(0)
  377. try:
  378. self._body = self.read()
  379. except OSError as e:
  380. raise UnreadablePostError(*e.args) from e
  381. finally:
  382. self._stream.close()
  383. self._stream = BytesIO(self._body)
  384. return self._body
  385. def _check_data_too_big(self, length):
  386. if (
  387. settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None
  388. and length > settings.DATA_UPLOAD_MAX_MEMORY_SIZE
  389. ):
  390. msg = "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE."
  391. raise RequestDataTooBig(msg)
  392. def _mark_post_parse_error(self):
  393. self._post = QueryDict()
  394. self._files = MultiValueDict()
  395. def _load_post_and_files(self):
  396. """
  397. Populate self._post and self._files if the content-type is a form type
  398. """
  399. if self.method != "POST":
  400. self._post, self._files = (
  401. QueryDict(encoding=self._encoding),
  402. MultiValueDict(),
  403. )
  404. return
  405. if self._read_started and not hasattr(self, "_body"):
  406. self._mark_post_parse_error()
  407. return
  408. if self.content_type == "multipart/form-data":
  409. if hasattr(self, "_body"):
  410. # Use already read data
  411. data = BytesIO(self._body)
  412. else:
  413. data = self
  414. try:
  415. self._post, self._files = self.parse_file_upload(self.META, data)
  416. except (MultiPartParserError, TooManyFilesSent):
  417. # An error occurred while parsing POST data. Since when
  418. # formatting the error the request handler might access
  419. # self.POST, set self._post and self._file to prevent
  420. # attempts to parse POST data again.
  421. self._mark_post_parse_error()
  422. raise
  423. elif self.content_type == "application/x-www-form-urlencoded":
  424. # According to RFC 1866, the "application/x-www-form-urlencoded"
  425. # content type does not have a charset and should be always treated
  426. # as UTF-8.
  427. if self._encoding is not None and self._encoding.lower() != "utf-8":
  428. raise BadRequest(
  429. "HTTP requests with the 'application/x-www-form-urlencoded' "
  430. "content type must be UTF-8 encoded."
  431. )
  432. self._post = QueryDict(self.body, encoding="utf-8")
  433. self._files = MultiValueDict()
  434. else:
  435. self._post, self._files = (
  436. QueryDict(encoding=self._encoding),
  437. MultiValueDict(),
  438. )
  439. def close(self):
  440. if hasattr(self, "_files"):
  441. for f in chain.from_iterable(list_[1] for list_ in self._files.lists()):
  442. f.close()
  443. # File-like and iterator interface.
  444. #
  445. # Expects self._stream to be set to an appropriate source of bytes by
  446. # a corresponding request subclass (e.g. WSGIRequest).
  447. # Also when request data has already been read by request.POST or
  448. # request.body, self._stream points to a BytesIO instance
  449. # containing that data.
  450. def read(self, *args, **kwargs):
  451. self._read_started = True
  452. try:
  453. return self._stream.read(*args, **kwargs)
  454. except OSError as e:
  455. raise UnreadablePostError(*e.args) from e
  456. def readline(self, *args, **kwargs):
  457. self._read_started = True
  458. try:
  459. return self._stream.readline(*args, **kwargs)
  460. except OSError as e:
  461. raise UnreadablePostError(*e.args) from e
  462. def __iter__(self):
  463. return iter(self.readline, b"")
  464. def readlines(self):
  465. return list(self)
  466. class HttpHeaders(CaseInsensitiveMapping):
  467. HTTP_PREFIX = "HTTP_"
  468. # PEP 333 gives two headers which aren't prepended with HTTP_.
  469. UNPREFIXED_HEADERS = {"CONTENT_TYPE", "CONTENT_LENGTH"}
  470. def __init__(self, environ):
  471. headers = {}
  472. for header, value in environ.items():
  473. name = self.parse_header_name(header)
  474. if name:
  475. headers[name] = value
  476. super().__init__(headers)
  477. def __getitem__(self, key):
  478. """Allow header lookup using underscores in place of hyphens."""
  479. return super().__getitem__(key.replace("_", "-"))
  480. @classmethod
  481. def parse_header_name(cls, header):
  482. if header.startswith(cls.HTTP_PREFIX):
  483. header = header.removeprefix(cls.HTTP_PREFIX)
  484. elif header not in cls.UNPREFIXED_HEADERS:
  485. return None
  486. return header.replace("_", "-").title()
  487. @classmethod
  488. def to_wsgi_name(cls, header):
  489. header = header.replace("-", "_").upper()
  490. if header in cls.UNPREFIXED_HEADERS:
  491. return header
  492. return f"{cls.HTTP_PREFIX}{header}"
  493. @classmethod
  494. def to_asgi_name(cls, header):
  495. return header.replace("-", "_").upper()
  496. @classmethod
  497. def to_wsgi_names(cls, headers):
  498. return {
  499. cls.to_wsgi_name(header_name): value
  500. for header_name, value in headers.items()
  501. }
  502. @classmethod
  503. def to_asgi_names(cls, headers):
  504. return {
  505. cls.to_asgi_name(header_name): value
  506. for header_name, value in headers.items()
  507. }
  508. class QueryDict(MultiValueDict):
  509. """
  510. A specialized MultiValueDict which represents a query string.
  511. A QueryDict can be used to represent GET or POST data. It subclasses
  512. MultiValueDict since keys in such data can be repeated, for instance
  513. in the data from a form with a <select multiple> field.
  514. By default QueryDicts are immutable, though the copy() method
  515. will always return a mutable copy.
  516. Both keys and values set on this class are converted from the given
  517. encoding (DEFAULT_CHARSET by default) to str.
  518. """
  519. # These are both reset in __init__, but is specified here at the class
  520. # level so that unpickling will have valid values
  521. _mutable = True
  522. _encoding = None
  523. def __init__(self, query_string=None, mutable=False, encoding=None):
  524. super().__init__()
  525. self.encoding = encoding or settings.DEFAULT_CHARSET
  526. query_string = query_string or ""
  527. parse_qsl_kwargs = {
  528. "keep_blank_values": True,
  529. "encoding": self.encoding,
  530. "max_num_fields": settings.DATA_UPLOAD_MAX_NUMBER_FIELDS,
  531. }
  532. if isinstance(query_string, bytes):
  533. # query_string normally contains URL-encoded data, a subset of
  534. # ASCII.
  535. try:
  536. query_string = query_string.decode(self.encoding)
  537. except UnicodeDecodeError:
  538. # ... but some user agents are misbehaving :-(
  539. query_string = query_string.decode("iso-8859-1")
  540. try:
  541. for key, value in parse_qsl(query_string, **parse_qsl_kwargs):
  542. self.appendlist(key, value)
  543. except ValueError as e:
  544. # ValueError can also be raised if the strict_parsing argument to
  545. # parse_qsl() is True. As that is not used by Django, assume that
  546. # the exception was raised by exceeding the value of max_num_fields
  547. # instead of fragile checks of exception message strings.
  548. raise TooManyFieldsSent(
  549. "The number of GET/POST parameters exceeded "
  550. "settings.DATA_UPLOAD_MAX_NUMBER_FIELDS."
  551. ) from e
  552. self._mutable = mutable
  553. @classmethod
  554. def fromkeys(cls, iterable, value="", mutable=False, encoding=None):
  555. """
  556. Return a new QueryDict with keys (may be repeated) from an iterable and
  557. values from value.
  558. """
  559. q = cls("", mutable=True, encoding=encoding)
  560. for key in iterable:
  561. q.appendlist(key, value)
  562. if not mutable:
  563. q._mutable = False
  564. return q
  565. @property
  566. def encoding(self):
  567. if self._encoding is None:
  568. self._encoding = settings.DEFAULT_CHARSET
  569. return self._encoding
  570. @encoding.setter
  571. def encoding(self, value):
  572. self._encoding = value
  573. def _assert_mutable(self):
  574. if not self._mutable:
  575. raise AttributeError("This QueryDict instance is immutable")
  576. def __setitem__(self, key, value):
  577. self._assert_mutable()
  578. key = bytes_to_text(key, self.encoding)
  579. value = bytes_to_text(value, self.encoding)
  580. super().__setitem__(key, value)
  581. def __delitem__(self, key):
  582. self._assert_mutable()
  583. super().__delitem__(key)
  584. def __copy__(self):
  585. result = self.__class__("", mutable=True, encoding=self.encoding)
  586. for key, value in self.lists():
  587. result.setlist(key, value)
  588. return result
  589. def __deepcopy__(self, memo):
  590. result = self.__class__("", mutable=True, encoding=self.encoding)
  591. memo[id(self)] = result
  592. for key, value in self.lists():
  593. result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo))
  594. return result
  595. def setlist(self, key, list_):
  596. self._assert_mutable()
  597. key = bytes_to_text(key, self.encoding)
  598. list_ = [bytes_to_text(elt, self.encoding) for elt in list_]
  599. super().setlist(key, list_)
  600. def setlistdefault(self, key, default_list=None):
  601. self._assert_mutable()
  602. return super().setlistdefault(key, default_list)
  603. def appendlist(self, key, value):
  604. self._assert_mutable()
  605. key = bytes_to_text(key, self.encoding)
  606. value = bytes_to_text(value, self.encoding)
  607. super().appendlist(key, value)
  608. def pop(self, key, *args):
  609. self._assert_mutable()
  610. return super().pop(key, *args)
  611. def popitem(self):
  612. self._assert_mutable()
  613. return super().popitem()
  614. def clear(self):
  615. self._assert_mutable()
  616. super().clear()
  617. def setdefault(self, key, default=None):
  618. self._assert_mutable()
  619. key = bytes_to_text(key, self.encoding)
  620. default = bytes_to_text(default, self.encoding)
  621. return super().setdefault(key, default)
  622. def copy(self):
  623. """Return a mutable copy of this object."""
  624. return self.__deepcopy__({})
  625. def urlencode(self, safe=None):
  626. """
  627. Return an encoded string of all query string arguments.
  628. `safe` specifies characters which don't require quoting, for example::
  629. >>> q = QueryDict(mutable=True)
  630. >>> q['next'] = '/a&b/'
  631. >>> q.urlencode()
  632. 'next=%2Fa%26b%2F'
  633. >>> q.urlencode(safe='/')
  634. 'next=/a%26b/'
  635. """
  636. output = []
  637. if safe:
  638. safe = safe.encode(self.encoding)
  639. def encode(k, v):
  640. return "%s=%s" % ((quote(k, safe), quote(v, safe)))
  641. else:
  642. def encode(k, v):
  643. return urlencode({k: v})
  644. for k, list_ in self.lists():
  645. output.extend(
  646. encode(k.encode(self.encoding), str(v).encode(self.encoding))
  647. for v in list_
  648. )
  649. return "&".join(output)
  650. class MediaType:
  651. def __init__(self, media_type_raw_line):
  652. full_type, self.params = parse_header_parameters(
  653. media_type_raw_line if media_type_raw_line else ""
  654. )
  655. self.main_type, _, self.sub_type = full_type.partition("/")
  656. def __str__(self):
  657. params_str = "".join("; %s=%s" % (k, v) for k, v in self.params.items())
  658. return "%s%s%s" % (
  659. self.main_type,
  660. ("/%s" % self.sub_type) if self.sub_type else "",
  661. params_str,
  662. )
  663. def __repr__(self):
  664. return "<%s: %s>" % (self.__class__.__qualname__, self)
  665. @cached_property
  666. def range_params(self):
  667. params = self.params.copy()
  668. params.pop("q", None)
  669. return params
  670. def match(self, other):
  671. if not other:
  672. return False
  673. if not isinstance(other, MediaType):
  674. other = MediaType(other)
  675. main_types = [self.main_type, other.main_type]
  676. sub_types = [self.sub_type, other.sub_type]
  677. # Main types and sub types must be defined.
  678. if not all((*main_types, *sub_types)):
  679. return False
  680. # Main types must match or one be "*", same for sub types.
  681. for this_type, other_type in (main_types, sub_types):
  682. if this_type != other_type and this_type != "*" and other_type != "*":
  683. return False
  684. if bool(self.range_params) == bool(other.range_params):
  685. # If both have params or neither have params, they must be
  686. # identical.
  687. result = self.range_params == other.range_params
  688. else:
  689. # If self has params and other does not, it's a match.
  690. # If other has params and self does not, don't match.
  691. result = bool(self.range_params or not other.range_params)
  692. return result
  693. @cached_property
  694. def quality(self):
  695. try:
  696. quality = float(self.params.get("q", 1))
  697. except ValueError:
  698. # Discard invalid values.
  699. return 1
  700. # Valid quality values must be between 0 and 1.
  701. if quality < 0 or quality > 1:
  702. return 1
  703. return round(quality, 3)
  704. @property
  705. def specificity(self):
  706. """
  707. Return a value from 0-3 for how specific the media type is.
  708. """
  709. if self.main_type == "*":
  710. return 0
  711. elif self.sub_type == "*":
  712. return 1
  713. elif not self.range_params:
  714. return 2
  715. return 3
  716. # It's neither necessary nor appropriate to use
  717. # django.utils.encoding.force_str() for parsing URLs and form inputs. Thus,
  718. # this slightly more restricted function, used by QueryDict.
  719. def bytes_to_text(s, encoding):
  720. """
  721. Convert bytes objects to strings, using the given encoding. Illegally
  722. encoded input characters are replaced with Unicode "unknown" codepoint
  723. (\ufffd).
  724. Return any non-bytes objects without change.
  725. """
  726. if isinstance(s, bytes):
  727. return str(s, encoding, "replace")
  728. else:
  729. return s
  730. def split_domain_port(host):
  731. """
  732. Return a (domain, port) tuple from a given host.
  733. Returned domain is lowercased. If the host is invalid, the domain will be
  734. empty.
  735. """
  736. if match := host_validation_re.fullmatch(host.lower()):
  737. domain, port = match.groups(default="")
  738. # Remove a trailing dot (if present) from the domain.
  739. return domain.removesuffix("."), port
  740. return "", ""
  741. def validate_host(host, allowed_hosts):
  742. """
  743. Validate the given host for this site.
  744. Check that the host looks valid and matches a host or host pattern in the
  745. given list of ``allowed_hosts``. Any pattern beginning with a period
  746. matches a domain and all its subdomains (e.g. ``.example.com`` matches
  747. ``example.com`` and any subdomain), ``*`` matches anything, and anything
  748. else must match exactly.
  749. Note: This function assumes that the given host is lowercased and has
  750. already had the port, if any, stripped off.
  751. Return ``True`` for a valid host, ``False`` otherwise.
  752. """
  753. return any(
  754. pattern == "*" or is_same_domain(host, pattern) for pattern in allowed_hosts
  755. )