response.py 19 KB

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