You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

response.py 17 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. from __future__ import unicode_literals
  2. import datetime
  3. import json
  4. import re
  5. import sys
  6. import time
  7. from email.header import Header
  8. from django.conf import settings
  9. from django.core import signals, signing
  10. from django.core.exceptions import DisallowedRedirect
  11. from django.core.serializers.json import DjangoJSONEncoder
  12. from django.http.cookie import SimpleCookie
  13. from django.utils import six, timezone
  14. from django.utils.encoding import (
  15. force_bytes, force_str, force_text, iri_to_uri,
  16. )
  17. from django.utils.http import cookie_date
  18. from django.utils.six.moves import map
  19. from django.utils.six.moves.http_client import responses
  20. from django.utils.six.moves.urllib.parse import urlparse
  21. _charset_from_content_type_re = re.compile(r';\s*charset=(?P<charset>[^\s;]+)', re.I)
  22. class BadHeaderError(ValueError):
  23. pass
  24. class HttpResponseBase(six.Iterator):
  25. """
  26. An HTTP response base class with dictionary-accessed headers.
  27. This class doesn't handle content. It should not be used directly.
  28. Use the HttpResponse and StreamingHttpResponse subclasses instead.
  29. """
  30. status_code = 200
  31. def __init__(self, content_type=None, status=None, reason=None, charset=None):
  32. # _headers is a mapping of the lower-case name to the original case of
  33. # the header (required for working with legacy systems) and the header
  34. # value. Both the name of the header and its value are ASCII strings.
  35. self._headers = {}
  36. self._closable_objects = []
  37. # This parameter is set by the handler. It's necessary to preserve the
  38. # historical behavior of request_finished.
  39. self._handler_class = None
  40. self.cookies = SimpleCookie()
  41. self.closed = False
  42. if status is not None:
  43. self.status_code = status
  44. self._reason_phrase = reason
  45. self._charset = charset
  46. if content_type is None:
  47. content_type = '%s; charset=%s' % (settings.DEFAULT_CONTENT_TYPE,
  48. self.charset)
  49. self['Content-Type'] = content_type
  50. @property
  51. def reason_phrase(self):
  52. if self._reason_phrase is not None:
  53. return self._reason_phrase
  54. # Leave self._reason_phrase unset in order to use the default
  55. # reason phrase for status code.
  56. return responses.get(self.status_code, 'Unknown Status Code')
  57. @reason_phrase.setter
  58. def reason_phrase(self, value):
  59. self._reason_phrase = value
  60. @property
  61. def charset(self):
  62. if self._charset is not None:
  63. return self._charset
  64. content_type = self.get('Content-Type', '')
  65. matched = _charset_from_content_type_re.search(content_type)
  66. if matched:
  67. # Extract the charset and strip its double quotes
  68. return matched.group('charset').replace('"', '')
  69. return settings.DEFAULT_CHARSET
  70. @charset.setter
  71. def charset(self, value):
  72. self._charset = value
  73. def serialize_headers(self):
  74. """HTTP headers as a bytestring."""
  75. def to_bytes(val, encoding):
  76. return val if isinstance(val, bytes) else val.encode(encoding)
  77. headers = [
  78. (b': '.join([to_bytes(key, 'ascii'), to_bytes(value, 'latin-1')]))
  79. for key, value in self._headers.values()
  80. ]
  81. return b'\r\n'.join(headers)
  82. if six.PY3:
  83. __bytes__ = serialize_headers
  84. else:
  85. __str__ = serialize_headers
  86. def _convert_to_charset(self, value, charset, mime_encode=False):
  87. """Converts headers key/value to ascii/latin-1 native strings.
  88. `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
  89. `value` can't be represented in the given charset, MIME-encoding
  90. is applied.
  91. """
  92. if not isinstance(value, (bytes, six.text_type)):
  93. value = str(value)
  94. if ((isinstance(value, bytes) and (b'\n' in value or b'\r' in value)) or
  95. isinstance(value, six.text_type) and ('\n' in value or '\r' in value)):
  96. raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
  97. try:
  98. if six.PY3:
  99. if isinstance(value, str):
  100. # Ensure string is valid in given charset
  101. value.encode(charset)
  102. else:
  103. # Convert bytestring using given charset
  104. value = value.decode(charset)
  105. else:
  106. if isinstance(value, str):
  107. # Ensure string is valid in given charset
  108. value.decode(charset)
  109. else:
  110. # Convert unicode string to given charset
  111. value = value.encode(charset)
  112. except UnicodeError as e:
  113. if mime_encode:
  114. # Wrapping in str() is a workaround for #12422 under Python 2.
  115. value = str(Header(value, 'utf-8', maxlinelen=sys.maxsize).encode())
  116. else:
  117. e.reason += ', HTTP response headers must be in %s format' % charset
  118. raise
  119. return value
  120. def __setitem__(self, header, value):
  121. header = self._convert_to_charset(header, 'ascii')
  122. value = self._convert_to_charset(value, 'latin-1', mime_encode=True)
  123. self._headers[header.lower()] = (header, value)
  124. def __delitem__(self, header):
  125. try:
  126. del self._headers[header.lower()]
  127. except KeyError:
  128. pass
  129. def __getitem__(self, header):
  130. return self._headers[header.lower()][1]
  131. def has_header(self, header):
  132. """Case-insensitive check for a header."""
  133. return header.lower() in self._headers
  134. __contains__ = has_header
  135. def items(self):
  136. return self._headers.values()
  137. def get(self, header, alternate=None):
  138. return self._headers.get(header.lower(), (None, alternate))[1]
  139. def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
  140. domain=None, secure=False, httponly=False):
  141. """
  142. Sets a cookie.
  143. ``expires`` can be:
  144. - a string in the correct format,
  145. - a naive ``datetime.datetime`` object in UTC,
  146. - an aware ``datetime.datetime`` object in any time zone.
  147. If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
  148. """
  149. value = force_str(value)
  150. self.cookies[key] = value
  151. if expires is not None:
  152. if isinstance(expires, datetime.datetime):
  153. if timezone.is_aware(expires):
  154. expires = timezone.make_naive(expires, timezone.utc)
  155. delta = expires - expires.utcnow()
  156. # Add one second so the date matches exactly (a fraction of
  157. # time gets lost between converting to a timedelta and
  158. # then the date string).
  159. delta = delta + datetime.timedelta(seconds=1)
  160. # Just set max_age - the max_age logic will set expires.
  161. expires = None
  162. max_age = max(0, delta.days * 86400 + delta.seconds)
  163. else:
  164. self.cookies[key]['expires'] = expires
  165. if max_age is not None:
  166. self.cookies[key]['max-age'] = max_age
  167. # IE requires expires, so set it if hasn't been already.
  168. if not expires:
  169. self.cookies[key]['expires'] = cookie_date(time.time() +
  170. max_age)
  171. if path is not None:
  172. self.cookies[key]['path'] = path
  173. if domain is not None:
  174. self.cookies[key]['domain'] = domain
  175. if secure:
  176. self.cookies[key]['secure'] = True
  177. if httponly:
  178. self.cookies[key]['httponly'] = True
  179. def setdefault(self, key, value):
  180. """Sets a header unless it has already been set."""
  181. if key not in self:
  182. self[key] = value
  183. def set_signed_cookie(self, key, value, salt='', **kwargs):
  184. value = signing.get_cookie_signer(salt=key + salt).sign(value)
  185. return self.set_cookie(key, value, **kwargs)
  186. def delete_cookie(self, key, path='/', domain=None):
  187. self.set_cookie(key, max_age=0, path=path, domain=domain,
  188. expires='Thu, 01-Jan-1970 00:00:00 GMT')
  189. # Common methods used by subclasses
  190. def make_bytes(self, value):
  191. """Turn a value into a bytestring encoded in the output charset."""
  192. # Per PEP 3333, this response body must be bytes. To avoid returning
  193. # an instance of a subclass, this function returns `bytes(value)`.
  194. # This doesn't make a copy when `value` already contains bytes.
  195. # Handle string types -- we can't rely on force_bytes here because:
  196. # - under Python 3 it attempts str conversion first
  197. # - when self._charset != 'utf-8' it re-encodes the content
  198. if isinstance(value, bytes):
  199. return bytes(value)
  200. if isinstance(value, six.text_type):
  201. return bytes(value.encode(self.charset))
  202. # Handle non-string types (#16494)
  203. return force_bytes(value, self.charset)
  204. # These methods partially implement the file-like object interface.
  205. # See https://docs.python.org/3/library/io.html#io.IOBase
  206. # The WSGI server must call this method upon completion of the request.
  207. # See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html
  208. def close(self):
  209. for closable in self._closable_objects:
  210. try:
  211. closable.close()
  212. except Exception:
  213. pass
  214. self.closed = True
  215. signals.request_finished.send(sender=self._handler_class)
  216. def write(self, content):
  217. raise IOError("This %s instance is not writable" % self.__class__.__name__)
  218. def flush(self):
  219. pass
  220. def tell(self):
  221. raise IOError("This %s instance cannot tell its position" % self.__class__.__name__)
  222. # These methods partially implement a stream-like object interface.
  223. # See https://docs.python.org/library/io.html#io.IOBase
  224. def writable(self):
  225. return False
  226. def writelines(self, lines):
  227. raise IOError("This %s instance is not writable" % self.__class__.__name__)
  228. class HttpResponse(HttpResponseBase):
  229. """
  230. An HTTP response class with a string as content.
  231. This content that can be read, appended to or replaced.
  232. """
  233. streaming = False
  234. def __init__(self, content=b'', *args, **kwargs):
  235. super(HttpResponse, self).__init__(*args, **kwargs)
  236. # Content is a bytestring. See the `content` property methods.
  237. self.content = content
  238. def __repr__(self):
  239. return '<%(cls)s status_code=%(status_code)d, "%(content_type)s">' % {
  240. 'cls': self.__class__.__name__,
  241. 'status_code': self.status_code,
  242. 'content_type': self['Content-Type'],
  243. }
  244. def serialize(self):
  245. """Full HTTP message, including headers, as a bytestring."""
  246. return self.serialize_headers() + b'\r\n\r\n' + self.content
  247. if six.PY3:
  248. __bytes__ = serialize
  249. else:
  250. __str__ = serialize
  251. @property
  252. def content(self):
  253. return b''.join(self._container)
  254. @content.setter
  255. def content(self, value):
  256. # Consume iterators upon assignment to allow repeated iteration.
  257. if hasattr(value, '__iter__') and not isinstance(value, (bytes, six.string_types)):
  258. if hasattr(value, 'close'):
  259. self._closable_objects.append(value)
  260. value = b''.join(self.make_bytes(chunk) for chunk in value)
  261. else:
  262. value = self.make_bytes(value)
  263. # Create a list of properly encoded bytestrings to support write().
  264. self._container = [value]
  265. def __iter__(self):
  266. return iter(self._container)
  267. def write(self, content):
  268. self._container.append(self.make_bytes(content))
  269. def tell(self):
  270. return len(self.content)
  271. def getvalue(self):
  272. return self.content
  273. def writable(self):
  274. return True
  275. def writelines(self, lines):
  276. for line in lines:
  277. self.write(line)
  278. class StreamingHttpResponse(HttpResponseBase):
  279. """
  280. A streaming HTTP response class with an iterator as content.
  281. This should only be iterated once, when the response is streamed to the
  282. client. However, it can be appended to or replaced with a new iterator
  283. that wraps the original content (or yields entirely new content).
  284. """
  285. streaming = True
  286. def __init__(self, streaming_content=(), *args, **kwargs):
  287. super(StreamingHttpResponse, self).__init__(*args, **kwargs)
  288. # `streaming_content` should be an iterable of bytestrings.
  289. # See the `streaming_content` property methods.
  290. self.streaming_content = streaming_content
  291. @property
  292. def content(self):
  293. raise AttributeError("This %s instance has no `content` attribute. "
  294. "Use `streaming_content` instead." % self.__class__.__name__)
  295. @property
  296. def streaming_content(self):
  297. return map(self.make_bytes, self._iterator)
  298. @streaming_content.setter
  299. def streaming_content(self, value):
  300. self._set_streaming_content(value)
  301. def _set_streaming_content(self, value):
  302. # Ensure we can never iterate on "value" more than once.
  303. self._iterator = iter(value)
  304. if hasattr(value, 'close'):
  305. self._closable_objects.append(value)
  306. def __iter__(self):
  307. return self.streaming_content
  308. def getvalue(self):
  309. return b''.join(self.streaming_content)
  310. class FileResponse(StreamingHttpResponse):
  311. """
  312. A streaming HTTP response class optimized for files.
  313. """
  314. block_size = 4096
  315. def _set_streaming_content(self, value):
  316. if hasattr(value, 'read'):
  317. self.file_to_stream = value
  318. filelike = value
  319. if hasattr(filelike, 'close'):
  320. self._closable_objects.append(filelike)
  321. value = iter(lambda: filelike.read(self.block_size), b'')
  322. else:
  323. self.file_to_stream = None
  324. super(FileResponse, self)._set_streaming_content(value)
  325. class HttpResponseRedirectBase(HttpResponse):
  326. allowed_schemes = ['http', 'https', 'ftp']
  327. def __init__(self, redirect_to, *args, **kwargs):
  328. parsed = urlparse(force_text(redirect_to))
  329. if parsed.scheme and parsed.scheme not in self.allowed_schemes:
  330. raise DisallowedRedirect("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
  331. super(HttpResponseRedirectBase, self).__init__(*args, **kwargs)
  332. self['Location'] = iri_to_uri(redirect_to)
  333. url = property(lambda self: self['Location'])
  334. def __repr__(self):
  335. return '<%(cls)s status_code=%(status_code)d, "%(content_type)s", url="%(url)s">' % {
  336. 'cls': self.__class__.__name__,
  337. 'status_code': self.status_code,
  338. 'content_type': self['Content-Type'],
  339. 'url': self.url,
  340. }
  341. class HttpResponseRedirect(HttpResponseRedirectBase):
  342. status_code = 302
  343. class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
  344. status_code = 301
  345. class HttpResponseNotModified(HttpResponse):
  346. status_code = 304
  347. def __init__(self, *args, **kwargs):
  348. super(HttpResponseNotModified, self).__init__(*args, **kwargs)
  349. del self['content-type']
  350. @HttpResponse.content.setter
  351. def content(self, value):
  352. if value:
  353. raise AttributeError("You cannot set content to a 304 (Not Modified) response")
  354. self._container = []
  355. class HttpResponseBadRequest(HttpResponse):
  356. status_code = 400
  357. class HttpResponseNotFound(HttpResponse):
  358. status_code = 404
  359. class HttpResponseForbidden(HttpResponse):
  360. status_code = 403
  361. class HttpResponseNotAllowed(HttpResponse):
  362. status_code = 405
  363. def __init__(self, permitted_methods, *args, **kwargs):
  364. super(HttpResponseNotAllowed, self).__init__(*args, **kwargs)
  365. self['Allow'] = ', '.join(permitted_methods)
  366. def __repr__(self):
  367. return '<%(cls)s [%(methods)s] status_code=%(status_code)d, "%(content_type)s">' % {
  368. 'cls': self.__class__.__name__,
  369. 'status_code': self.status_code,
  370. 'content_type': self['Content-Type'],
  371. 'methods': self['Allow'],
  372. }
  373. class HttpResponseGone(HttpResponse):
  374. status_code = 410
  375. class HttpResponseServerError(HttpResponse):
  376. status_code = 500
  377. class Http404(Exception):
  378. pass
  379. class JsonResponse(HttpResponse):
  380. """
  381. An HTTP response class that consumes data to be serialized to JSON.
  382. :param data: Data to be dumped into json. By default only ``dict`` objects
  383. are allowed to be passed due to a security flaw before EcmaScript 5. See
  384. the ``safe`` parameter for more information.
  385. :param encoder: Should be an json encoder class. Defaults to
  386. ``django.core.serializers.json.DjangoJSONEncoder``.
  387. :param safe: Controls if only ``dict`` objects may be serialized. Defaults
  388. to ``True``.
  389. :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
  390. """
  391. def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
  392. json_dumps_params=None, **kwargs):
  393. if safe and not isinstance(data, dict):
  394. raise TypeError('In order to allow non-dict objects to be '
  395. 'serialized set the safe parameter to False')
  396. if json_dumps_params is None:
  397. json_dumps_params = {}
  398. kwargs.setdefault('content_type', 'application/json')
  399. data = json.dumps(data, cls=encoder, **json_dumps_params)
  400. super(JsonResponse, self).__init__(content=data, **kwargs)