http_headers.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 __future__ import division, absolute_import
  8. from twisted.python.compat import comparable, cmp, unicode
  9. def _dashCapitalize(name):
  10. """
  11. Return a byte string which is capitalized using '-' as a word separator.
  12. @param name: The name of the header to capitalize.
  13. @type name: L{bytes}
  14. @return: The given header capitalized using '-' as a word separator.
  15. @rtype: L{bytes}
  16. """
  17. return b'-'.join([word.capitalize() for word in name.split(b'-')])
  18. @comparable
  19. class Headers(object):
  20. """
  21. Stores HTTP headers in a key and multiple value format.
  22. Most methods accept L{bytes} and L{unicode}, with an internal L{bytes}
  23. representation. When passed L{unicode}, header names (e.g. 'Content-Type')
  24. are encoded using ISO-8859-1 and header values (e.g.
  25. 'text/html;charset=utf-8') are encoded using UTF-8. Some methods that return
  26. values will return them in the same type as the name given.
  27. If the header keys or values cannot be encoded or decoded using the rules
  28. above, using just L{bytes} arguments to the methods of this class will
  29. ensure no decoding or encoding is done, and L{Headers} will treat the keys
  30. and values as opaque byte strings.
  31. @cvar _caseMappings: A L{dict} that maps lowercase header names
  32. to their canonicalized representation.
  33. @ivar _rawHeaders: A L{dict} mapping header names as L{bytes} to L{list}s of
  34. header values as L{bytes}.
  35. """
  36. _caseMappings = {
  37. b'content-md5': b'Content-MD5',
  38. b'dnt': b'DNT',
  39. b'etag': b'ETag',
  40. b'p3p': b'P3P',
  41. b'te': b'TE',
  42. b'www-authenticate': b'WWW-Authenticate',
  43. b'x-xss-protection': b'X-XSS-Protection'}
  44. def __init__(self, rawHeaders=None):
  45. self._rawHeaders = {}
  46. if rawHeaders is not None:
  47. for name, values in rawHeaders.items():
  48. self.setRawHeaders(name, values)
  49. def __repr__(self):
  50. """
  51. Return a string fully describing the headers set on this object.
  52. """
  53. return '%s(%r)' % (self.__class__.__name__, self._rawHeaders,)
  54. def __cmp__(self, other):
  55. """
  56. Define L{Headers} instances as being equal to each other if they have
  57. the same raw headers.
  58. """
  59. if isinstance(other, Headers):
  60. return cmp(
  61. sorted(self._rawHeaders.items()),
  62. sorted(other._rawHeaders.items()))
  63. return NotImplemented
  64. def _encodeName(self, name):
  65. """
  66. Encode the name of a header (eg 'Content-Type') to an ISO-8859-1 encoded
  67. bytestring if required.
  68. @param name: A HTTP header name
  69. @type name: L{unicode} or L{bytes}
  70. @return: C{name}, encoded if required, lowercased
  71. @rtype: L{bytes}
  72. """
  73. if isinstance(name, unicode):
  74. return name.lower().encode('iso-8859-1')
  75. return name.lower()
  76. def _encodeValue(self, value):
  77. """
  78. Encode a single header value to a UTF-8 encoded bytestring if required.
  79. @param value: A single HTTP header value.
  80. @type value: L{bytes} or L{unicode}
  81. @return: C{value}, encoded if required
  82. @rtype: L{bytes}
  83. """
  84. if isinstance(value, unicode):
  85. return value.encode('utf8')
  86. return value
  87. def _encodeValues(self, values):
  88. """
  89. Encode a L{list} of header values to a L{list} of UTF-8 encoded
  90. bytestrings if required.
  91. @param values: A list of HTTP header values.
  92. @type values: L{list} of L{bytes} or L{unicode} (mixed types allowed)
  93. @return: C{values}, with each item encoded if required
  94. @rtype: L{list} of L{bytes}
  95. """
  96. newValues = []
  97. for value in values:
  98. newValues.append(self._encodeValue(value))
  99. return newValues
  100. def _decodeValues(self, values):
  101. """
  102. Decode a L{list} of header values into a L{list} of Unicode strings.
  103. @param values: A list of HTTP header values.
  104. @type values: L{list} of UTF-8 encoded L{bytes}
  105. @return: C{values}, with each item decoded
  106. @rtype: L{list} of L{unicode}
  107. """
  108. newValues = []
  109. for value in values:
  110. newValues.append(value.decode('utf8'))
  111. return newValues
  112. def copy(self):
  113. """
  114. Return a copy of itself with the same headers set.
  115. @return: A new L{Headers}
  116. """
  117. return self.__class__(self._rawHeaders)
  118. def hasHeader(self, name):
  119. """
  120. Check for the existence of a given header.
  121. @type name: L{bytes} or L{unicode}
  122. @param name: The name of the HTTP header to check for.
  123. @rtype: L{bool}
  124. @return: C{True} if the header exists, otherwise C{False}.
  125. """
  126. return self._encodeName(name) in self._rawHeaders
  127. def removeHeader(self, name):
  128. """
  129. Remove the named header from this header object.
  130. @type name: L{bytes} or L{unicode}
  131. @param name: The name of the HTTP header to remove.
  132. @return: L{None}
  133. """
  134. self._rawHeaders.pop(self._encodeName(name), None)
  135. def setRawHeaders(self, name, values):
  136. """
  137. Sets the raw representation of the given header.
  138. @type name: L{bytes} or L{unicode}
  139. @param name: The name of the HTTP header to set the values for.
  140. @type values: L{list} of L{bytes} or L{unicode} strings
  141. @param values: A list of strings each one being a header value of
  142. the given name.
  143. @return: L{None}
  144. """
  145. if not isinstance(values, list):
  146. raise TypeError("Header entry %r should be list but found "
  147. "instance of %r instead" % (name, type(values)))
  148. name = self._encodeName(name)
  149. self._rawHeaders[name] = self._encodeValues(values)
  150. def addRawHeader(self, name, value):
  151. """
  152. Add a new raw value for the given header.
  153. @type name: L{bytes} or L{unicode}
  154. @param name: The name of the header for which to set the value.
  155. @type value: L{bytes} or L{unicode}
  156. @param value: The value to set for the named header.
  157. """
  158. values = self.getRawHeaders(name)
  159. if values is not None:
  160. values.append(value)
  161. else:
  162. values = [value]
  163. self.setRawHeaders(name, values)
  164. def getRawHeaders(self, name, default=None):
  165. """
  166. Returns a list of headers matching the given name as the raw string
  167. given.
  168. @type name: L{bytes} or L{unicode}
  169. @param name: The name of the HTTP header to get the values of.
  170. @param default: The value to return if no header with the given C{name}
  171. exists.
  172. @rtype: L{list} of strings, same type as C{name} (except when
  173. C{default} is returned).
  174. @return: If the named header is present, a L{list} of its
  175. values. Otherwise, C{default}.
  176. """
  177. encodedName = self._encodeName(name)
  178. values = self._rawHeaders.get(encodedName, default)
  179. if isinstance(name, unicode) and values is not default:
  180. return self._decodeValues(values)
  181. return values
  182. def getAllRawHeaders(self):
  183. """
  184. Return an iterator of key, value pairs of all headers contained in this
  185. object, as L{bytes}. The keys are capitalized in canonical
  186. capitalization.
  187. """
  188. for k, v in self._rawHeaders.items():
  189. yield self._canonicalNameCaps(k), v
  190. def _canonicalNameCaps(self, name):
  191. """
  192. Return the canonical name for the given header.
  193. @type name: L{bytes}
  194. @param name: The all-lowercase header name to capitalize in its
  195. canonical form.
  196. @rtype: L{bytes}
  197. @return: The canonical name of the header.
  198. """
  199. return self._caseMappings.get(name, _dashCapitalize(name))
  200. __all__ = ['Headers']