Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

request.py 24KB

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