PageRenderTime 37ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/wsgiref/headers.py

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