headers.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. """Manage HTTP Response Headers
  2. Much of this module is red-handedly pilfered from email.message in the stdlib,
  3. so portions are Copyright (C) 2001,2002 Python Software Foundation, and were
  4. written by Barry Warsaw.
  5. """
  6. # Regular expression that matches `special' characters in parameters, the
  7. # existence of which force quoting of the parameter value.
  8. import re
  9. tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
  10. def _formatparam(param, value=None, quote=1):
  11. """Convenience function to format and return a key=value pair.
  12. This will quote the value if needed or if quote is true.
  13. """
  14. if value is not None and len(value) > 0:
  15. if quote or tspecials.search(value):
  16. value = value.replace('\\', '\\\\').replace('"', r'\"')
  17. return '%s="%s"' % (param, value)
  18. else:
  19. return '%s=%s' % (param, value)
  20. else:
  21. return param
  22. class Headers:
  23. """Manage a collection of HTTP response headers"""
  24. def __init__(self, headers=None):
  25. headers = headers if headers is not None else []
  26. if type(headers) is not list:
  27. raise TypeError("Headers must be a list of name/value tuples")
  28. self._headers = headers
  29. if __debug__:
  30. for k, v in headers:
  31. self._convert_string_type(k)
  32. self._convert_string_type(v)
  33. def _convert_string_type(self, value):
  34. """Convert/check value type."""
  35. if type(value) is str:
  36. return value
  37. raise AssertionError("Header names/values must be"
  38. " of type str (got {0})".format(repr(value)))
  39. def __len__(self):
  40. """Return the total number of headers, including duplicates."""
  41. return len(self._headers)
  42. def __setitem__(self, name, val):
  43. """Set the value of a header."""
  44. del self[name]
  45. self._headers.append(
  46. (self._convert_string_type(name), self._convert_string_type(val)))
  47. def __delitem__(self,name):
  48. """Delete all occurrences of a header, if present.
  49. Does *not* raise an exception if the header is missing.
  50. """
  51. name = self._convert_string_type(name.lower())
  52. self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name]
  53. def __getitem__(self,name):
  54. """Get the first header value for 'name'
  55. Return None if the header is missing instead of raising an exception.
  56. Note that if the header appeared multiple times, the first exactly which
  57. occurrence gets returned is undefined. Use getall() to get all
  58. the values matching a header field name.
  59. """
  60. return self.get(name)
  61. def __contains__(self, name):
  62. """Return true if the message contains the header."""
  63. return self.get(name) is not None
  64. def get_all(self, name):
  65. """Return a list of all the values for the named field.
  66. These will be sorted in the order they appeared in the original header
  67. list or were added to this instance, and may contain duplicates. Any
  68. fields deleted and re-inserted are always appended to the header list.
  69. If no fields exist with the given name, returns an empty list.
  70. """
  71. name = self._convert_string_type(name.lower())
  72. return [kv[1] for kv in self._headers if kv[0].lower()==name]
  73. def get(self,name,default=None):
  74. """Get the first header value for 'name', or return 'default'"""
  75. name = self._convert_string_type(name.lower())
  76. for k,v in self._headers:
  77. if k.lower()==name:
  78. return v
  79. return default
  80. def keys(self):
  81. """Return a list of all the header field names.
  82. These will be sorted in the order they appeared in the original header
  83. list, or were added to this instance, and may contain duplicates.
  84. Any fields deleted and re-inserted are always appended to the header
  85. list.
  86. """
  87. return [k for k, v in self._headers]
  88. def values(self):
  89. """Return a list of all header values.
  90. These will be sorted in the order they appeared in the original header
  91. list, or were added to this instance, and may contain duplicates.
  92. Any fields deleted and re-inserted are always appended to the header
  93. list.
  94. """
  95. return [v for k, v in self._headers]
  96. def items(self):
  97. """Get all the header fields and values.
  98. These will be sorted in the order they were in the original header
  99. list, or were added to this instance, and may contain duplicates.
  100. Any fields deleted and re-inserted are always appended to the header
  101. list.
  102. """
  103. return self._headers[:]
  104. def __repr__(self):
  105. return "%s(%r)" % (self.__class__.__name__, self._headers)
  106. def __str__(self):
  107. """str() returns the formatted headers, complete with end line,
  108. suitable for direct HTTP transmission."""
  109. return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['',''])
  110. def __bytes__(self):
  111. return str(self).encode('iso-8859-1')
  112. def setdefault(self,name,value):
  113. """Return first matching header value for 'name', or 'value'
  114. If there is no header named 'name', add a new header with name 'name'
  115. and value 'value'."""
  116. result = self.get(name)
  117. if result is None:
  118. self._headers.append((self._convert_string_type(name),
  119. self._convert_string_type(value)))
  120. return value
  121. else:
  122. return result
  123. def add_header(self, _name, _value, **_params):
  124. """Extended header setting.
  125. _name is the header field to add. keyword arguments can be used to set
  126. additional parameters for the header field, with underscores converted
  127. to dashes. Normally the parameter will be added as key="value" unless
  128. value is None, in which case only the key will be added.
  129. Example:
  130. h.add_header('content-disposition', 'attachment', filename='bud.gif')
  131. Note that unlike the corresponding 'email.message' method, this does
  132. *not* handle '(charset, language, value)' tuples: all values must be
  133. strings or None.
  134. """
  135. parts = []
  136. if _value is not None:
  137. _value = self._convert_string_type(_value)
  138. parts.append(_value)
  139. for k, v in _params.items():
  140. k = self._convert_string_type(k)
  141. if v is None:
  142. parts.append(k.replace('_', '-'))
  143. else:
  144. v = self._convert_string_type(v)
  145. parts.append(_formatparam(k.replace('_', '-'), v))
  146. self._headers.append((self._convert_string_type(_name), "; ".join(parts)))