PageRenderTime 58ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/django-1.5/django/http/response.py

https://github.com/theosp/google_appengine
Python | 447 lines | 398 code | 10 blank | 39 comment | 10 complexity | 891f7f7500471f8738ab412a48694469 MD5 | raw file
  1. from __future__ import absolute_import, unicode_literals
  2. import datetime
  3. import time
  4. import warnings
  5. from email.header import Header
  6. try:
  7. from urllib.parse import urlparse
  8. except ImportError:
  9. from urlparse import urlparse
  10. from django.conf import settings
  11. from django.core import signals
  12. from django.core import signing
  13. from django.core.exceptions import SuspiciousOperation
  14. from django.http.cookie import SimpleCookie
  15. from django.utils import six, timezone
  16. from django.utils.encoding import force_bytes, iri_to_uri
  17. from django.utils.http import cookie_date
  18. from django.utils.six.moves import map
  19. class BadHeaderError(ValueError):
  20. pass
  21. class HttpResponseBase(six.Iterator):
  22. """
  23. An HTTP response base class with dictionary-accessed headers.
  24. This class doesn't handle content. It should not be used directly.
  25. Use the HttpResponse and StreamingHttpResponse subclasses instead.
  26. """
  27. status_code = 200
  28. def __init__(self, content_type=None, status=None, mimetype=None):
  29. # _headers is a mapping of the lower-case name to the original case of
  30. # the header (required for working with legacy systems) and the header
  31. # value. Both the name of the header and its value are ASCII strings.
  32. self._headers = {}
  33. self._charset = settings.DEFAULT_CHARSET
  34. self._closable_objects = []
  35. # This parameter is set by the handler. It's necessary to preserve the
  36. # historical behavior of request_finished.
  37. self._handler_class = None
  38. if mimetype:
  39. warnings.warn("Using mimetype keyword argument is deprecated, use"
  40. " content_type instead", PendingDeprecationWarning)
  41. content_type = mimetype
  42. if not content_type:
  43. content_type = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE,
  44. self._charset)
  45. self.cookies = SimpleCookie()
  46. if status:
  47. self.status_code = status
  48. self['Content-Type'] = content_type
  49. def serialize_headers(self):
  50. """HTTP headers as a bytestring."""
  51. headers = [
  52. ('%s: %s' % (key, value)).encode('us-ascii')
  53. for key, value in self._headers.values()
  54. ]
  55. return b'\r\n'.join(headers)
  56. if six.PY3:
  57. __bytes__ = serialize_headers
  58. else:
  59. __str__ = serialize_headers
  60. def _convert_to_charset(self, value, charset, mime_encode=False):
  61. """Converts headers key/value to ascii/latin1 native strings.
  62. `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
  63. `value` value can't be represented in the given charset, MIME-encoding
  64. is applied.
  65. """
  66. if not isinstance(value, (bytes, six.text_type)):
  67. value = str(value)
  68. try:
  69. if six.PY3:
  70. if isinstance(value, str):
  71. # Ensure string is valid in given charset
  72. value.encode(charset)
  73. else:
  74. # Convert bytestring using given charset
  75. value = value.decode(charset)
  76. else:
  77. if isinstance(value, str):
  78. # Ensure string is valid in given charset
  79. value.decode(charset)
  80. else:
  81. # Convert unicode string to given charset
  82. value = value.encode(charset)
  83. except UnicodeError as e:
  84. if mime_encode:
  85. # Wrapping in str() is a workaround for #12422 under Python 2.
  86. value = str(Header(value, 'utf-8').encode())
  87. else:
  88. e.reason += ', HTTP response headers must be in %s format' % charset
  89. raise
  90. if str('\n') in value or str('\r') in value:
  91. raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
  92. return value
  93. def __setitem__(self, header, value):
  94. header = self._convert_to_charset(header, 'ascii')
  95. value = self._convert_to_charset(value, 'latin1', mime_encode=True)
  96. self._headers[header.lower()] = (header, value)
  97. def __delitem__(self, header):
  98. try:
  99. del self._headers[header.lower()]
  100. except KeyError:
  101. pass
  102. def __getitem__(self, header):
  103. return self._headers[header.lower()][1]
  104. def __getstate__(self):
  105. # SimpleCookie is not pickeable with pickle.HIGHEST_PROTOCOL, so we
  106. # serialise to a string instead
  107. state = self.__dict__.copy()
  108. state['cookies'] = str(state['cookies'])
  109. return state
  110. def __setstate__(self, state):
  111. self.__dict__.update(state)
  112. self.cookies = SimpleCookie(self.cookies)
  113. def has_header(self, header):
  114. """Case-insensitive check for a header."""
  115. return header.lower() in self._headers
  116. __contains__ = has_header
  117. def items(self):
  118. return self._headers.values()
  119. def get(self, header, alternate=None):
  120. return self._headers.get(header.lower(), (None, alternate))[1]
  121. def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
  122. domain=None, secure=False, httponly=False):
  123. """
  124. Sets a cookie.
  125. ``expires`` can be:
  126. - a string in the correct format,
  127. - a naive ``datetime.datetime`` object in UTC,
  128. - an aware ``datetime.datetime`` object in any time zone.
  129. If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
  130. """
  131. self.cookies[key] = value
  132. if expires is not None:
  133. if isinstance(expires, datetime.datetime):
  134. if timezone.is_aware(expires):
  135. expires = timezone.make_naive(expires, timezone.utc)
  136. delta = expires - expires.utcnow()
  137. # Add one second so the date matches exactly (a fraction of
  138. # time gets lost between converting to a timedelta and
  139. # then the date string).
  140. delta = delta + datetime.timedelta(seconds=1)
  141. # Just set max_age - the max_age logic will set expires.
  142. expires = None
  143. max_age = max(0, delta.days * 86400 + delta.seconds)
  144. else:
  145. self.cookies[key]['expires'] = expires
  146. if max_age is not None:
  147. self.cookies[key]['max-age'] = max_age
  148. # IE requires expires, so set it if hasn't been already.
  149. if not expires:
  150. self.cookies[key]['expires'] = cookie_date(time.time() +
  151. max_age)
  152. if path is not None:
  153. self.cookies[key]['path'] = path
  154. if domain is not None:
  155. self.cookies[key]['domain'] = domain
  156. if secure:
  157. self.cookies[key]['secure'] = True
  158. if httponly:
  159. self.cookies[key]['httponly'] = True
  160. def set_signed_cookie(self, key, value, salt='', **kwargs):
  161. value = signing.get_cookie_signer(salt=key + salt).sign(value)
  162. return self.set_cookie(key, value, **kwargs)
  163. def delete_cookie(self, key, path='/', domain=None):
  164. self.set_cookie(key, max_age=0, path=path, domain=domain,
  165. expires='Thu, 01-Jan-1970 00:00:00 GMT')
  166. # Common methods used by subclasses
  167. def make_bytes(self, value):
  168. """Turn a value into a bytestring encoded in the output charset."""
  169. # Per PEP 3333, this response body must be bytes. To avoid returning
  170. # an instance of a subclass, this function returns `bytes(value)`.
  171. # This doesn't make a copy when `value` already contains bytes.
  172. # If content is already encoded (eg. gzip), assume bytes.
  173. if self.has_header('Content-Encoding'):
  174. return bytes(value)
  175. # Handle string types -- we can't rely on force_bytes here because:
  176. # - under Python 3 it attemps str conversion first
  177. # - when self._charset != 'utf-8' it re-encodes the content
  178. if isinstance(value, bytes):
  179. return bytes(value)
  180. if isinstance(value, six.text_type):
  181. return bytes(value.encode(self._charset))
  182. # Handle non-string types (#16494)
  183. return force_bytes(value, self._charset)
  184. def __iter__(self):
  185. return self
  186. def __next__(self):
  187. # Subclasses must define self._iterator for this function.
  188. return self.make_bytes(next(self._iterator))
  189. # These methods partially implement the file-like object interface.
  190. # See http://docs.python.org/lib/bltin-file-objects.html
  191. # The WSGI server must call this method upon completion of the request.
  192. # See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html
  193. def close(self):
  194. for closable in self._closable_objects:
  195. try:
  196. closable.close()
  197. except Exception:
  198. pass
  199. signals.request_finished.send(sender=self._handler_class)
  200. def write(self, content):
  201. raise Exception("This %s instance is not writable" % self.__class__.__name__)
  202. def flush(self):
  203. pass
  204. def tell(self):
  205. raise Exception("This %s instance cannot tell its position" % self.__class__.__name__)
  206. class HttpResponse(HttpResponseBase):
  207. """
  208. An HTTP response class with a string as content.
  209. This content that can be read, appended to or replaced.
  210. """
  211. streaming = False
  212. def __init__(self, content='', *args, **kwargs):
  213. super(HttpResponse, self).__init__(*args, **kwargs)
  214. # Content is a bytestring. See the `content` property methods.
  215. self.content = content
  216. def serialize(self):
  217. """Full HTTP message, including headers, as a bytestring."""
  218. return self.serialize_headers() + b'\r\n\r\n' + self.content
  219. if six.PY3:
  220. __bytes__ = serialize
  221. else:
  222. __str__ = serialize
  223. def _consume_content(self):
  224. # If the response was instantiated with an iterator, when its content
  225. # is accessed, the iterator is going be exhausted and the content
  226. # loaded in memory. At this point, it's better to abandon the original
  227. # iterator and save the content for later reuse. This is a temporary
  228. # solution. See the comment in __iter__ below for the long term plan.
  229. if self._base_content_is_iter:
  230. self.content = b''.join(self.make_bytes(e) for e in self._container)
  231. @property
  232. def content(self):
  233. self._consume_content()
  234. return b''.join(self.make_bytes(e) for e in self._container)
  235. @content.setter
  236. def content(self, value):
  237. if hasattr(value, '__iter__') and not isinstance(value, (bytes, six.string_types)):
  238. self._container = value
  239. self._base_content_is_iter = True
  240. if hasattr(value, 'close'):
  241. self._closable_objects.append(value)
  242. else:
  243. self._container = [value]
  244. self._base_content_is_iter = False
  245. def __iter__(self):
  246. # Raise a deprecation warning only if the content wasn't consumed yet,
  247. # because the response may be intended to be streamed.
  248. # Once the deprecation completes, iterators should be consumed upon
  249. # assignment rather than upon access. The _consume_content method
  250. # should be removed. See #6527.
  251. if self._base_content_is_iter:
  252. warnings.warn(
  253. 'Creating streaming responses with `HttpResponse` is '
  254. 'deprecated. Use `StreamingHttpResponse` instead '
  255. 'if you need the streaming behavior.',
  256. PendingDeprecationWarning, stacklevel=2)
  257. if not hasattr(self, '_iterator'):
  258. self._iterator = iter(self._container)
  259. return self
  260. def write(self, content):
  261. self._consume_content()
  262. self._container.append(content)
  263. def tell(self):
  264. self._consume_content()
  265. return len(self.content)
  266. class StreamingHttpResponse(HttpResponseBase):
  267. """
  268. A streaming HTTP response class with an iterator as content.
  269. This should only be iterated once, when the response is streamed to the
  270. client. However, it can be appended to or replaced with a new iterator
  271. that wraps the original content (or yields entirely new content).
  272. """
  273. streaming = True
  274. def __init__(self, streaming_content=(), *args, **kwargs):
  275. super(StreamingHttpResponse, self).__init__(*args, **kwargs)
  276. # `streaming_content` should be an iterable of bytestrings.
  277. # See the `streaming_content` property methods.
  278. self.streaming_content = streaming_content
  279. @property
  280. def content(self):
  281. raise AttributeError("This %s instance has no `content` attribute. "
  282. "Use `streaming_content` instead." % self.__class__.__name__)
  283. @property
  284. def streaming_content(self):
  285. return map(self.make_bytes, self._iterator)
  286. @streaming_content.setter
  287. def streaming_content(self, value):
  288. # Ensure we can never iterate on "value" more than once.
  289. self._iterator = iter(value)
  290. if hasattr(value, 'close'):
  291. self._closable_objects.append(value)
  292. class CompatibleStreamingHttpResponse(StreamingHttpResponse):
  293. """
  294. This class maintains compatibility with middleware that doesn't know how
  295. to handle the content of a streaming response by exposing a `content`
  296. attribute that will consume and cache the content iterator when accessed.
  297. These responses will stream only if no middleware attempts to access the
  298. `content` attribute. Otherwise, they will behave like a regular response,
  299. and raise a `PendingDeprecationWarning`.
  300. """
  301. @property
  302. def content(self):
  303. warnings.warn(
  304. 'Accessing the `content` attribute on a streaming response is '
  305. 'deprecated. Use the `streaming_content` attribute instead.',
  306. PendingDeprecationWarning)
  307. content = b''.join(self)
  308. self.streaming_content = [content]
  309. return content
  310. @content.setter
  311. def content(self, content):
  312. warnings.warn(
  313. 'Accessing the `content` attribute on a streaming response is '
  314. 'deprecated. Use the `streaming_content` attribute instead.',
  315. PendingDeprecationWarning)
  316. self.streaming_content = [content]
  317. class HttpResponseRedirectBase(HttpResponse):
  318. allowed_schemes = ['http', 'https', 'ftp']
  319. def __init__(self, redirect_to, *args, **kwargs):
  320. parsed = urlparse(redirect_to)
  321. if parsed.scheme and parsed.scheme not in self.allowed_schemes:
  322. raise SuspiciousOperation("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
  323. super(HttpResponseRedirectBase, self).__init__(*args, **kwargs)
  324. self['Location'] = iri_to_uri(redirect_to)
  325. class HttpResponseRedirect(HttpResponseRedirectBase):
  326. status_code = 302
  327. class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
  328. status_code = 301
  329. class HttpResponseNotModified(HttpResponse):
  330. status_code = 304
  331. def __init__(self, *args, **kwargs):
  332. super(HttpResponseNotModified, self).__init__(*args, **kwargs)
  333. del self['content-type']
  334. @HttpResponse.content.setter
  335. def content(self, value):
  336. if value:
  337. raise AttributeError("You cannot set content to a 304 (Not Modified) response")
  338. self._container = []
  339. self._base_content_is_iter = False
  340. class HttpResponseBadRequest(HttpResponse):
  341. status_code = 400
  342. class HttpResponseNotFound(HttpResponse):
  343. status_code = 404
  344. class HttpResponseForbidden(HttpResponse):
  345. status_code = 403
  346. class HttpResponseNotAllowed(HttpResponse):
  347. status_code = 405
  348. def __init__(self, permitted_methods, *args, **kwargs):
  349. super(HttpResponseNotAllowed, self).__init__(*args, **kwargs)
  350. self['Allow'] = ', '.join(permitted_methods)
  351. class HttpResponseGone(HttpResponse):
  352. status_code = 410
  353. class HttpResponseServerError(HttpResponse):
  354. status_code = 500
  355. class Http404(Exception):
  356. pass