response.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
  2. # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
  3. """Routines to generate WSGI responses"""
  4. ############################################################
  5. ## Headers
  6. ############################################################
  7. import warnings
  8. class HeaderDict(dict):
  9. """
  10. This represents response headers. It handles the headers as a
  11. dictionary, with case-insensitive keys.
  12. Also there is an ``.add(key, value)`` method, which sets the key,
  13. or adds the value to the current value (turning it into a list if
  14. necessary).
  15. For passing to WSGI there is a ``.headeritems()`` method which is
  16. like ``.items()`` but unpacks value that are lists. It also
  17. handles encoding -- all headers are encoded in ASCII (if they are
  18. unicode).
  19. @@: Should that encoding be ISO-8859-1 or UTF-8? I'm not sure
  20. what the spec says.
  21. """
  22. def __getitem__(self, key):
  23. return dict.__getitem__(self, self.normalize(key))
  24. def __setitem__(self, key, value):
  25. dict.__setitem__(self, self.normalize(key), value)
  26. def __delitem__(self, key):
  27. dict.__delitem__(self, self.normalize(key))
  28. def __contains__(self, key):
  29. return dict.__contains__(self, self.normalize(key))
  30. has_key = __contains__
  31. def get(self, key, failobj=None):
  32. return dict.get(self, self.normalize(key), failobj)
  33. def setdefault(self, key, failobj=None):
  34. return dict.setdefault(self, self.normalize(key), failobj)
  35. def pop(self, key, *args):
  36. return dict.pop(self, self.normalize(key), *args)
  37. def update(self, other):
  38. for key in other:
  39. self[self.normalize(key)] = other[key]
  40. def normalize(self, key):
  41. return str(key).lower().strip()
  42. def add(self, key, value):
  43. key = self.normalize(key)
  44. if key in self:
  45. if isinstance(self[key], list):
  46. self[key].append(value)
  47. else:
  48. self[key] = [self[key], value]
  49. else:
  50. self[key] = value
  51. def headeritems(self):
  52. result = []
  53. for key, value in self.items():
  54. if isinstance(value, list):
  55. for v in value:
  56. result.append((key, str(v)))
  57. else:
  58. result.append((key, str(value)))
  59. return result
  60. #@classmethod
  61. def fromlist(cls, seq):
  62. self = cls()
  63. for name, value in seq:
  64. self.add(name, value)
  65. return self
  66. fromlist = classmethod(fromlist)
  67. def has_header(headers, name):
  68. """
  69. Is header named ``name`` present in headers?
  70. """
  71. name = name.lower()
  72. for header, value in headers:
  73. if header.lower() == name:
  74. return True
  75. return False
  76. def header_value(headers, name):
  77. """
  78. Returns the header's value, or None if no such header. If a
  79. header appears more than once, all the values of the headers
  80. are joined with ','. Note that this is consistent /w RFC 2616
  81. section 4.2 which states:
  82. It MUST be possible to combine the multiple header fields
  83. into one "field-name: field-value" pair, without changing
  84. the semantics of the message, by appending each subsequent
  85. field-value to the first, each separated by a comma.
  86. However, note that the original netscape usage of 'Set-Cookie',
  87. especially in MSIE which contains an 'expires' date will is not
  88. compatible with this particular concatination method.
  89. """
  90. name = name.lower()
  91. result = [value for header, value in headers
  92. if header.lower() == name]
  93. if result:
  94. return ','.join(result)
  95. else:
  96. return None
  97. def remove_header(headers, name):
  98. """
  99. Removes the named header from the list of headers. Returns the
  100. value of that header, or None if no header found. If multiple
  101. headers are found, only the last one is returned.
  102. """
  103. name = name.lower()
  104. i = 0
  105. result = None
  106. while i < len(headers):
  107. if headers[i][0].lower() == name:
  108. result = headers[i][1]
  109. del headers[i]
  110. continue
  111. i += 1
  112. return result
  113. def replace_header(headers, name, value):
  114. """
  115. Updates the headers replacing the first occurance of the given name
  116. with the value provided; asserting that no further occurances
  117. happen. Note that this is _not_ the same as remove_header and then
  118. append, as two distinct operations (del followed by an append) are
  119. not atomic in a threaded environment. Returns the previous header
  120. value for the provided name, if any. Clearly one should not use
  121. this function with ``set-cookie`` or other names that may have more
  122. than one occurance in the headers.
  123. """
  124. name = name.lower()
  125. i = 0
  126. result = None
  127. while i < len(headers):
  128. if headers[i][0].lower() == name:
  129. assert not result, "two values for the header '%s' found" % name
  130. result = headers[i][1]
  131. headers[i] = (name, value)
  132. i += 1
  133. if not result:
  134. headers.append((name, value))
  135. return result
  136. ############################################################
  137. ## Deprecated methods
  138. ############################################################
  139. def error_body_response(error_code, message, __warn=True):
  140. """
  141. Returns a standard HTML response page for an HTTP error.
  142. **Note:** Deprecated
  143. """
  144. if __warn:
  145. warnings.warn(
  146. 'wsgilib.error_body_response is deprecated; use the '
  147. 'wsgi_application method on an HTTPException object '
  148. 'instead', DeprecationWarning, 2)
  149. return '''\
  150. <html>
  151. <head>
  152. <title>%(error_code)s</title>
  153. </head>
  154. <body>
  155. <h1>%(error_code)s</h1>
  156. %(message)s
  157. </body>
  158. </html>''' % {
  159. 'error_code': error_code,
  160. 'message': message,
  161. }
  162. def error_response(environ, error_code, message,
  163. debug_message=None, __warn=True):
  164. """
  165. Returns the status, headers, and body of an error response.
  166. Use like:
  167. .. code-block:: python
  168. status, headers, body = wsgilib.error_response(
  169. '301 Moved Permanently', 'Moved to <a href="%s">%s</a>'
  170. % (url, url))
  171. start_response(status, headers)
  172. return [body]
  173. **Note:** Deprecated
  174. """
  175. if __warn:
  176. warnings.warn(
  177. 'wsgilib.error_response is deprecated; use the '
  178. 'wsgi_application method on an HTTPException object '
  179. 'instead', DeprecationWarning, 2)
  180. if debug_message and environ.get('paste.config', {}).get('debug'):
  181. message += '\n\n<!-- %s -->' % debug_message
  182. body = error_body_response(error_code, message, __warn=False)
  183. headers = [('content-type', 'text/html'),
  184. ('content-length', str(len(body)))]
  185. return error_code, headers, body
  186. def error_response_app(error_code, message, debug_message=None,
  187. __warn=True):
  188. """
  189. An application that emits the given error response.
  190. **Note:** Deprecated
  191. """
  192. if __warn:
  193. warnings.warn(
  194. 'wsgilib.error_response_app is deprecated; use the '
  195. 'wsgi_application method on an HTTPException object '
  196. 'instead', DeprecationWarning, 2)
  197. def application(environ, start_response):
  198. status, headers, body = error_response(
  199. environ, error_code, message,
  200. debug_message=debug_message, __warn=False)
  201. start_response(status, headers)
  202. return [body]
  203. return application