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.

http_headers.py 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. # -*- test-case-name: twisted.web.test.test_http_headers -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. An API for storing HTTP header names and values.
  6. """
  7. from collections.abc import Sequence as _Sequence
  8. from typing import (
  9. AnyStr,
  10. Dict,
  11. Iterator,
  12. List,
  13. Mapping,
  14. Optional,
  15. Sequence,
  16. Tuple,
  17. TypeVar,
  18. Union,
  19. overload,
  20. )
  21. from twisted.python.compat import cmp, comparable
  22. _T = TypeVar("_T")
  23. def _dashCapitalize(name: bytes) -> bytes:
  24. """
  25. Return a byte string which is capitalized using '-' as a word separator.
  26. @param name: The name of the header to capitalize.
  27. @return: The given header capitalized using '-' as a word separator.
  28. """
  29. return b"-".join([word.capitalize() for word in name.split(b"-")])
  30. def _sanitizeLinearWhitespace(headerComponent: bytes) -> bytes:
  31. r"""
  32. Replace linear whitespace (C{\n}, C{\r\n}, C{\r}) in a header key
  33. or value with a single space.
  34. @param headerComponent: The header key or value to sanitize.
  35. @return: The sanitized header key or value.
  36. """
  37. return b" ".join(headerComponent.splitlines())
  38. @comparable
  39. class Headers:
  40. """
  41. Stores HTTP headers in a key and multiple value format.
  42. When passed L{str}, header names (e.g. 'Content-Type')
  43. are encoded using ISO-8859-1 and header values (e.g.
  44. 'text/html;charset=utf-8') are encoded using UTF-8. Some methods that return
  45. values will return them in the same type as the name given.
  46. If the header keys or values cannot be encoded or decoded using the rules
  47. above, using just L{bytes} arguments to the methods of this class will
  48. ensure no decoding or encoding is done, and L{Headers} will treat the keys
  49. and values as opaque byte strings.
  50. @cvar _caseMappings: A L{dict} that maps lowercase header names
  51. to their canonicalized representation.
  52. @ivar _rawHeaders: A L{dict} mapping header names as L{bytes} to L{list}s of
  53. header values as L{bytes}.
  54. """
  55. _caseMappings = {
  56. b"content-md5": b"Content-MD5",
  57. b"dnt": b"DNT",
  58. b"etag": b"ETag",
  59. b"p3p": b"P3P",
  60. b"te": b"TE",
  61. b"www-authenticate": b"WWW-Authenticate",
  62. b"x-xss-protection": b"X-XSS-Protection",
  63. }
  64. def __init__(
  65. self,
  66. rawHeaders: Optional[Mapping[AnyStr, Sequence[AnyStr]]] = None,
  67. ) -> None:
  68. self._rawHeaders: Dict[bytes, List[bytes]] = {}
  69. if rawHeaders is not None:
  70. for name, values in rawHeaders.items():
  71. self.setRawHeaders(name, values)
  72. def __repr__(self) -> str:
  73. """
  74. Return a string fully describing the headers set on this object.
  75. """
  76. return "{}({!r})".format(
  77. self.__class__.__name__,
  78. self._rawHeaders,
  79. )
  80. def __cmp__(self, other):
  81. """
  82. Define L{Headers} instances as being equal to each other if they have
  83. the same raw headers.
  84. """
  85. if isinstance(other, Headers):
  86. return cmp(
  87. sorted(self._rawHeaders.items()), sorted(other._rawHeaders.items())
  88. )
  89. return NotImplemented
  90. def _encodeName(self, name: Union[str, bytes]) -> bytes:
  91. """
  92. Encode the name of a header (eg 'Content-Type') to an ISO-8859-1 encoded
  93. bytestring if required.
  94. @param name: A HTTP header name
  95. @return: C{name}, encoded if required, lowercased
  96. """
  97. if isinstance(name, str):
  98. return name.lower().encode("iso-8859-1")
  99. return name.lower()
  100. def copy(self):
  101. """
  102. Return a copy of itself with the same headers set.
  103. @return: A new L{Headers}
  104. """
  105. return self.__class__(self._rawHeaders)
  106. def hasHeader(self, name: AnyStr) -> bool:
  107. """
  108. Check for the existence of a given header.
  109. @param name: The name of the HTTP header to check for.
  110. @return: C{True} if the header exists, otherwise C{False}.
  111. """
  112. return self._encodeName(name) in self._rawHeaders
  113. def removeHeader(self, name: AnyStr) -> None:
  114. """
  115. Remove the named header from this header object.
  116. @param name: The name of the HTTP header to remove.
  117. @return: L{None}
  118. """
  119. self._rawHeaders.pop(self._encodeName(name), None)
  120. @overload
  121. def setRawHeaders(self, name: Union[str, bytes], values: Sequence[bytes]) -> None:
  122. ...
  123. @overload
  124. def setRawHeaders(self, name: Union[str, bytes], values: Sequence[str]) -> None:
  125. ...
  126. @overload
  127. def setRawHeaders(
  128. self, name: Union[str, bytes], values: Sequence[Union[str, bytes]]
  129. ) -> None:
  130. ...
  131. def setRawHeaders(self, name: Union[str, bytes], values: object) -> None:
  132. """
  133. Sets the raw representation of the given header.
  134. @param name: The name of the HTTP header to set the values for.
  135. @param values: A list of strings each one being a header value of
  136. the given name.
  137. @raise TypeError: Raised if C{values} is not a sequence of L{bytes}
  138. or L{str}, or if C{name} is not L{bytes} or L{str}.
  139. @return: L{None}
  140. """
  141. if not isinstance(values, _Sequence):
  142. raise TypeError(
  143. "Header entry %r should be sequence but found "
  144. "instance of %r instead" % (name, type(values))
  145. )
  146. if not isinstance(name, (bytes, str)):
  147. raise TypeError(
  148. f"Header name is an instance of {type(name)!r}, not bytes or str"
  149. )
  150. for count, value in enumerate(values):
  151. if not isinstance(value, (bytes, str)):
  152. raise TypeError(
  153. "Header value at position %s is an instance of %r, not "
  154. "bytes or str"
  155. % (
  156. count,
  157. type(value),
  158. )
  159. )
  160. _name = _sanitizeLinearWhitespace(self._encodeName(name))
  161. encodedValues: List[bytes] = []
  162. for v in values:
  163. if isinstance(v, str):
  164. _v = v.encode("utf8")
  165. else:
  166. _v = v
  167. encodedValues.append(_sanitizeLinearWhitespace(_v))
  168. self._rawHeaders[_name] = encodedValues
  169. def addRawHeader(self, name: Union[str, bytes], value: Union[str, bytes]) -> None:
  170. """
  171. Add a new raw value for the given header.
  172. @param name: The name of the header for which to set the value.
  173. @param value: The value to set for the named header.
  174. """
  175. if not isinstance(name, (bytes, str)):
  176. raise TypeError(
  177. f"Header name is an instance of {type(name)!r}, not bytes or str"
  178. )
  179. if not isinstance(value, (bytes, str)):
  180. raise TypeError(
  181. "Header value is an instance of %r, not "
  182. "bytes or str" % (type(value),)
  183. )
  184. self._rawHeaders.setdefault(
  185. _sanitizeLinearWhitespace(self._encodeName(name)), []
  186. ).append(
  187. _sanitizeLinearWhitespace(
  188. value.encode("utf8") if isinstance(value, str) else value
  189. )
  190. )
  191. @overload
  192. def getRawHeaders(self, name: AnyStr) -> Optional[Sequence[AnyStr]]:
  193. ...
  194. @overload
  195. def getRawHeaders(self, name: AnyStr, default: _T) -> Union[Sequence[AnyStr], _T]:
  196. ...
  197. def getRawHeaders(
  198. self, name: AnyStr, default: Optional[_T] = None
  199. ) -> Union[Sequence[AnyStr], Optional[_T]]:
  200. """
  201. Returns a sequence of headers matching the given name as the raw string
  202. given.
  203. @param name: The name of the HTTP header to get the values of.
  204. @param default: The value to return if no header with the given C{name}
  205. exists.
  206. @return: If the named header is present, a sequence of its
  207. values. Otherwise, C{default}.
  208. """
  209. encodedName = self._encodeName(name)
  210. values = self._rawHeaders.get(encodedName, [])
  211. if not values:
  212. return default
  213. if isinstance(name, str):
  214. return [v.decode("utf8") for v in values]
  215. return values
  216. def getAllRawHeaders(self) -> Iterator[Tuple[bytes, Sequence[bytes]]]:
  217. """
  218. Return an iterator of key, value pairs of all headers contained in this
  219. object, as L{bytes}. The keys are capitalized in canonical
  220. capitalization.
  221. """
  222. for k, v in self._rawHeaders.items():
  223. yield self._canonicalNameCaps(k), v
  224. def _canonicalNameCaps(self, name: bytes) -> bytes:
  225. """
  226. Return the canonical name for the given header.
  227. @param name: The all-lowercase header name to capitalize in its
  228. canonical form.
  229. @return: The canonical name of the header.
  230. """
  231. return self._caseMappings.get(name, _dashCapitalize(name))
  232. __all__ = ["Headers"]