PageRenderTime 68ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/django/http/__init__.py

https://bitbucket.org/pcelta/python-django
Python | 842 lines | 799 code | 16 blank | 27 comment | 25 complexity | 64c59fa3b0e98e0a345a22acc1b24561 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from __future__ import absolute_import
  2. import datetime
  3. import os
  4. import re
  5. import sys
  6. import time
  7. import warnings
  8. from pprint import pformat
  9. from urllib import urlencode, quote
  10. from urlparse import urljoin, urlparse
  11. try:
  12. from cStringIO import StringIO
  13. except ImportError:
  14. from StringIO import StringIO
  15. try:
  16. # The mod_python version is more efficient, so try importing it first.
  17. from mod_python.util import parse_qsl
  18. except ImportError:
  19. try:
  20. # Python 2.6 and greater
  21. from urlparse import parse_qsl
  22. except ImportError:
  23. # Python 2.5. Works on Python 2.6 but raises PendingDeprecationWarning
  24. from cgi import parse_qsl
  25. import Cookie
  26. # httponly support exists in Python 2.6's Cookie library,
  27. # but not in Python 2.5.
  28. _morsel_supports_httponly = 'httponly' in Cookie.Morsel._reserved
  29. # Some versions of Python 2.7 and later won't need this encoding bug fix:
  30. _cookie_encodes_correctly = Cookie.SimpleCookie().value_encode(';') == (';', '"\\073"')
  31. # See ticket #13007, http://bugs.python.org/issue2193 and http://trac.edgewall.org/ticket/2256
  32. _tc = Cookie.SimpleCookie()
  33. try:
  34. _tc.load('foo:bar=1')
  35. _cookie_allows_colon_in_names = True
  36. except Cookie.CookieError:
  37. _cookie_allows_colon_in_names = False
  38. if _morsel_supports_httponly and _cookie_encodes_correctly and _cookie_allows_colon_in_names:
  39. SimpleCookie = Cookie.SimpleCookie
  40. else:
  41. if not _morsel_supports_httponly:
  42. class Morsel(Cookie.Morsel):
  43. def __setitem__(self, K, V):
  44. K = K.lower()
  45. if K == "httponly":
  46. if V:
  47. # The superclass rejects httponly as a key,
  48. # so we jump to the grandparent.
  49. super(Cookie.Morsel, self).__setitem__(K, V)
  50. else:
  51. super(Morsel, self).__setitem__(K, V)
  52. def OutputString(self, attrs=None):
  53. output = super(Morsel, self).OutputString(attrs)
  54. if "httponly" in self:
  55. output += "; httponly"
  56. return output
  57. else:
  58. Morsel = Cookie.Morsel
  59. class SimpleCookie(Cookie.SimpleCookie):
  60. if not _cookie_encodes_correctly:
  61. def value_encode(self, val):
  62. # Some browsers do not support quoted-string from RFC 2109,
  63. # including some versions of Safari and Internet Explorer.
  64. # These browsers split on ';', and some versions of Safari
  65. # are known to split on ', '. Therefore, we encode ';' and ','
  66. # SimpleCookie already does the hard work of encoding and decoding.
  67. # It uses octal sequences like '\\012' for newline etc.
  68. # and non-ASCII chars. We just make use of this mechanism, to
  69. # avoid introducing two encoding schemes which would be confusing
  70. # and especially awkward for javascript.
  71. # NB, contrary to Python docs, value_encode returns a tuple containing
  72. # (real val, encoded_val)
  73. val, encoded = super(SimpleCookie, self).value_encode(val)
  74. encoded = encoded.replace(";", "\\073").replace(",","\\054")
  75. # If encoded now contains any quoted chars, we need double quotes
  76. # around the whole string.
  77. if "\\" in encoded and not encoded.startswith('"'):
  78. encoded = '"' + encoded + '"'
  79. return val, encoded
  80. if not _cookie_allows_colon_in_names or not _morsel_supports_httponly:
  81. def load(self, rawdata):
  82. self.bad_cookies = set()
  83. super(SimpleCookie, self).load(rawdata)
  84. for key in self.bad_cookies:
  85. del self[key]
  86. # override private __set() method:
  87. # (needed for using our Morsel, and for laxness with CookieError
  88. def _BaseCookie__set(self, key, real_value, coded_value):
  89. try:
  90. M = self.get(key, Morsel())
  91. M.set(key, real_value, coded_value)
  92. dict.__setitem__(self, key, M)
  93. except Cookie.CookieError:
  94. self.bad_cookies.add(key)
  95. dict.__setitem__(self, key, Cookie.Morsel())
  96. class CompatCookie(SimpleCookie):
  97. def __init__(self, *args, **kwargs):
  98. super(CompatCookie, self).__init__(*args, **kwargs)
  99. warnings.warn("CompatCookie is deprecated. Use django.http.SimpleCookie instead.", DeprecationWarning)
  100. from django.conf import settings
  101. from django.core import signing
  102. from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
  103. from django.core.files import uploadhandler
  104. from django.http.multipartparser import MultiPartParser
  105. from django.http.utils import *
  106. from django.utils.datastructures import MultiValueDict, ImmutableList
  107. from django.utils.encoding import smart_str, iri_to_uri, force_unicode
  108. from django.utils.http import cookie_date
  109. from django.utils import timezone
  110. RESERVED_CHARS="!*'();:@&=+$,/?%#[]"
  111. absolute_http_url_re = re.compile(r"^https?://", re.I)
  112. host_validation_re = re.compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9:]+\])(:\d+)?$")
  113. class Http404(Exception):
  114. pass
  115. RAISE_ERROR = object()
  116. def build_request_repr(request, path_override=None, GET_override=None,
  117. POST_override=None, COOKIES_override=None,
  118. META_override=None):
  119. """
  120. Builds and returns the request's representation string. The request's
  121. attributes may be overridden by pre-processed values.
  122. """
  123. # Since this is called as part of error handling, we need to be very
  124. # robust against potentially malformed input.
  125. try:
  126. get = (pformat(GET_override)
  127. if GET_override is not None
  128. else pformat(request.GET))
  129. except:
  130. get = '<could not parse>'
  131. if request._post_parse_error:
  132. post = '<could not parse>'
  133. else:
  134. try:
  135. post = (pformat(POST_override)
  136. if POST_override is not None
  137. else pformat(request.POST))
  138. except:
  139. post = '<could not parse>'
  140. try:
  141. cookies = (pformat(COOKIES_override)
  142. if COOKIES_override is not None
  143. else pformat(request.COOKIES))
  144. except:
  145. cookies = '<could not parse>'
  146. try:
  147. meta = (pformat(META_override)
  148. if META_override is not None
  149. else pformat(request.META))
  150. except:
  151. meta = '<could not parse>'
  152. path = path_override if path_override is not None else request.path
  153. return smart_str(u'<%s\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' %
  154. (request.__class__.__name__,
  155. path,
  156. unicode(get),
  157. unicode(post),
  158. unicode(cookies),
  159. unicode(meta)))
  160. class UnreadablePostError(IOError):
  161. pass
  162. class HttpRequest(object):
  163. """A basic HTTP request."""
  164. # The encoding used in GET/POST dicts. None means use default setting.
  165. _encoding = None
  166. _upload_handlers = []
  167. def __init__(self):
  168. self.GET, self.POST, self.COOKIES, self.META, self.FILES = {}, {}, {}, {}, {}
  169. self.path = ''
  170. self.path_info = ''
  171. self.method = None
  172. self._post_parse_error = False
  173. def __repr__(self):
  174. return build_request_repr(self)
  175. def get_host(self):
  176. """Returns the HTTP host using the environment or request headers."""
  177. # We try three options, in order of decreasing preference.
  178. if settings.USE_X_FORWARDED_HOST and (
  179. 'HTTP_X_FORWARDED_HOST' in self.META):
  180. host = self.META['HTTP_X_FORWARDED_HOST']
  181. elif 'HTTP_HOST' in self.META:
  182. host = self.META['HTTP_HOST']
  183. else:
  184. # Reconstruct the host using the algorithm from PEP 333.
  185. host = self.META['SERVER_NAME']
  186. server_port = str(self.META['SERVER_PORT'])
  187. if server_port != (self.is_secure() and '443' or '80'):
  188. host = '%s:%s' % (host, server_port)
  189. allowed_hosts = ['*'] if settings.DEBUG else settings.ALLOWED_HOSTS
  190. if validate_host(host, allowed_hosts):
  191. return host
  192. else:
  193. raise SuspiciousOperation(
  194. "Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s" % host)
  195. def get_full_path(self):
  196. # RFC 3986 requires query string arguments to be in the ASCII range.
  197. # Rather than crash if this doesn't happen, we encode defensively.
  198. return '%s%s' % (self.path, self.META.get('QUERY_STRING', '') and ('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) or '')
  199. def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
  200. """
  201. Attempts to return a signed cookie. If the signature fails or the
  202. cookie has expired, raises an exception... unless you provide the
  203. default argument in which case that value will be returned instead.
  204. """
  205. try:
  206. cookie_value = self.COOKIES[key].encode('utf-8')
  207. except KeyError:
  208. if default is not RAISE_ERROR:
  209. return default
  210. else:
  211. raise
  212. try:
  213. value = signing.get_cookie_signer(salt=key + salt).unsign(
  214. cookie_value, max_age=max_age)
  215. except signing.BadSignature:
  216. if default is not RAISE_ERROR:
  217. return default
  218. else:
  219. raise
  220. return value
  221. def build_absolute_uri(self, location=None):
  222. """
  223. Builds an absolute URI from the location and the variables available in
  224. this request. If no location is specified, the absolute URI is built on
  225. ``request.get_full_path()``.
  226. """
  227. if not location:
  228. location = self.get_full_path()
  229. if not absolute_http_url_re.match(location):
  230. current_uri = '%s://%s%s' % (self.is_secure() and 'https' or 'http',
  231. self.get_host(), self.path)
  232. location = urljoin(current_uri, location)
  233. return iri_to_uri(location)
  234. def _is_secure(self):
  235. return os.environ.get("HTTPS") == "on"
  236. def is_secure(self):
  237. # First, check the SECURE_PROXY_SSL_HEADER setting.
  238. if settings.SECURE_PROXY_SSL_HEADER:
  239. try:
  240. header, value = settings.SECURE_PROXY_SSL_HEADER
  241. except ValueError:
  242. raise ImproperlyConfigured('The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.')
  243. if self.META.get(header, None) == value:
  244. return True
  245. # Failing that, fall back to _is_secure(), which is a hook for
  246. # subclasses to implement.
  247. return self._is_secure()
  248. def is_ajax(self):
  249. return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
  250. def _set_encoding(self, val):
  251. """
  252. Sets the encoding used for GET/POST accesses. If the GET or POST
  253. dictionary has already been created, it is removed and recreated on the
  254. next access (so that it is decoded correctly).
  255. """
  256. self._encoding = val
  257. if hasattr(self, '_get'):
  258. del self._get
  259. if hasattr(self, '_post'):
  260. del self._post
  261. def _get_encoding(self):
  262. return self._encoding
  263. encoding = property(_get_encoding, _set_encoding)
  264. def _initialize_handlers(self):
  265. self._upload_handlers = [uploadhandler.load_handler(handler, self)
  266. for handler in settings.FILE_UPLOAD_HANDLERS]
  267. def _set_upload_handlers(self, upload_handlers):
  268. if hasattr(self, '_files'):
  269. raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
  270. self._upload_handlers = upload_handlers
  271. def _get_upload_handlers(self):
  272. if not self._upload_handlers:
  273. # If there are no upload handlers defined, initialize them from settings.
  274. self._initialize_handlers()
  275. return self._upload_handlers
  276. upload_handlers = property(_get_upload_handlers, _set_upload_handlers)
  277. def parse_file_upload(self, META, post_data):
  278. """Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
  279. self.upload_handlers = ImmutableList(
  280. self.upload_handlers,
  281. warning = "You cannot alter upload handlers after the upload has been processed."
  282. )
  283. parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
  284. return parser.parse()
  285. @property
  286. def body(self):
  287. if not hasattr(self, '_body'):
  288. if self._read_started:
  289. raise Exception("You cannot access body after reading from request's data stream")
  290. try:
  291. self._body = self.read()
  292. except IOError, e:
  293. raise UnreadablePostError, e, sys.exc_traceback
  294. self._stream = StringIO(self._body)
  295. return self._body
  296. @property
  297. def raw_post_data(self):
  298. warnings.warn('HttpRequest.raw_post_data has been deprecated. Use HttpRequest.body instead.', PendingDeprecationWarning)
  299. return self.body
  300. def _mark_post_parse_error(self):
  301. self._post = QueryDict('')
  302. self._files = MultiValueDict()
  303. self._post_parse_error = True
  304. def _load_post_and_files(self):
  305. # Populates self._post and self._files
  306. if self.method != 'POST':
  307. self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()
  308. return
  309. if self._read_started and not hasattr(self, '_body'):
  310. self._mark_post_parse_error()
  311. return
  312. if self.META.get('CONTENT_TYPE', '').startswith('multipart'):
  313. if hasattr(self, '_body'):
  314. # Use already read data
  315. data = StringIO(self._body)
  316. else:
  317. data = self
  318. try:
  319. self._post, self._files = self.parse_file_upload(self.META, data)
  320. except:
  321. # An error occured while parsing POST data. Since when
  322. # formatting the error the request handler might access
  323. # self.POST, set self._post and self._file to prevent
  324. # attempts to parse POST data again.
  325. # Mark that an error occured. This allows self.__repr__ to
  326. # be explicit about it instead of simply representing an
  327. # empty POST
  328. self._mark_post_parse_error()
  329. raise
  330. else:
  331. self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
  332. ## File-like and iterator interface.
  333. ##
  334. ## Expects self._stream to be set to an appropriate source of bytes by
  335. ## a corresponding request subclass (WSGIRequest or ModPythonRequest).
  336. ## Also when request data has already been read by request.POST or
  337. ## request.body, self._stream points to a StringIO instance
  338. ## containing that data.
  339. def read(self, *args, **kwargs):
  340. self._read_started = True
  341. return self._stream.read(*args, **kwargs)
  342. def readline(self, *args, **kwargs):
  343. self._read_started = True
  344. return self._stream.readline(*args, **kwargs)
  345. def xreadlines(self):
  346. while True:
  347. buf = self.readline()
  348. if not buf:
  349. break
  350. yield buf
  351. __iter__ = xreadlines
  352. def readlines(self):
  353. return list(iter(self))
  354. class QueryDict(MultiValueDict):
  355. """
  356. A specialized MultiValueDict that takes a query string when initialized.
  357. This is immutable unless you create a copy of it.
  358. Values retrieved from this class are converted from the given encoding
  359. (DEFAULT_CHARSET by default) to unicode.
  360. """
  361. # These are both reset in __init__, but is specified here at the class
  362. # level so that unpickling will have valid values
  363. _mutable = True
  364. _encoding = None
  365. def __init__(self, query_string, mutable=False, encoding=None):
  366. MultiValueDict.__init__(self)
  367. if not encoding:
  368. encoding = settings.DEFAULT_CHARSET
  369. self.encoding = encoding
  370. for key, value in parse_qsl((query_string or ''), True): # keep_blank_values=True
  371. self.appendlist(force_unicode(key, encoding, errors='replace'),
  372. force_unicode(value, encoding, errors='replace'))
  373. self._mutable = mutable
  374. def _get_encoding(self):
  375. if self._encoding is None:
  376. self._encoding = settings.DEFAULT_CHARSET
  377. return self._encoding
  378. def _set_encoding(self, value):
  379. self._encoding = value
  380. encoding = property(_get_encoding, _set_encoding)
  381. def _assert_mutable(self):
  382. if not self._mutable:
  383. raise AttributeError("This QueryDict instance is immutable")
  384. def __setitem__(self, key, value):
  385. self._assert_mutable()
  386. key = str_to_unicode(key, self.encoding)
  387. value = str_to_unicode(value, self.encoding)
  388. MultiValueDict.__setitem__(self, key, value)
  389. def __delitem__(self, key):
  390. self._assert_mutable()
  391. super(QueryDict, self).__delitem__(key)
  392. def __copy__(self):
  393. result = self.__class__('', mutable=True, encoding=self.encoding)
  394. for key, value in dict.items(self):
  395. dict.__setitem__(result, key, value)
  396. return result
  397. def __deepcopy__(self, memo):
  398. import copy
  399. result = self.__class__('', mutable=True, encoding=self.encoding)
  400. memo[id(self)] = result
  401. for key, value in dict.items(self):
  402. dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo))
  403. return result
  404. def setlist(self, key, list_):
  405. self._assert_mutable()
  406. key = str_to_unicode(key, self.encoding)
  407. list_ = [str_to_unicode(elt, self.encoding) for elt in list_]
  408. MultiValueDict.setlist(self, key, list_)
  409. def setlistdefault(self, key, default_list=()):
  410. self._assert_mutable()
  411. if key not in self:
  412. self.setlist(key, default_list)
  413. return MultiValueDict.getlist(self, key)
  414. def appendlist(self, key, value):
  415. self._assert_mutable()
  416. key = str_to_unicode(key, self.encoding)
  417. value = str_to_unicode(value, self.encoding)
  418. MultiValueDict.appendlist(self, key, value)
  419. def update(self, other_dict):
  420. self._assert_mutable()
  421. f = lambda s: str_to_unicode(s, self.encoding)
  422. if hasattr(other_dict, 'lists'):
  423. for key, valuelist in other_dict.lists():
  424. for value in valuelist:
  425. MultiValueDict.update(self, {f(key): f(value)})
  426. else:
  427. d = dict([(f(k), f(v)) for k, v in other_dict.items()])
  428. MultiValueDict.update(self, d)
  429. def pop(self, key, *args):
  430. self._assert_mutable()
  431. return MultiValueDict.pop(self, key, *args)
  432. def popitem(self):
  433. self._assert_mutable()
  434. return MultiValueDict.popitem(self)
  435. def clear(self):
  436. self._assert_mutable()
  437. MultiValueDict.clear(self)
  438. def setdefault(self, key, default=None):
  439. self._assert_mutable()
  440. key = str_to_unicode(key, self.encoding)
  441. default = str_to_unicode(default, self.encoding)
  442. return MultiValueDict.setdefault(self, key, default)
  443. def copy(self):
  444. """Returns a mutable copy of this object."""
  445. return self.__deepcopy__({})
  446. def urlencode(self, safe=None):
  447. """
  448. Returns an encoded string of all query string arguments.
  449. :arg safe: Used to specify characters which do not require quoting, for
  450. example::
  451. >>> q = QueryDict('', mutable=True)
  452. >>> q['next'] = '/a&b/'
  453. >>> q.urlencode()
  454. 'next=%2Fa%26b%2F'
  455. >>> q.urlencode(safe='/')
  456. 'next=/a%26b/'
  457. """
  458. output = []
  459. if safe:
  460. encode = lambda k, v: '%s=%s' % ((quote(k, safe), quote(v, safe)))
  461. else:
  462. encode = lambda k, v: urlencode({k: v})
  463. for k, list_ in self.lists():
  464. k = smart_str(k, self.encoding)
  465. output.extend([encode(k, smart_str(v, self.encoding))
  466. for v in list_])
  467. return '&'.join(output)
  468. def parse_cookie(cookie):
  469. if cookie == '':
  470. return {}
  471. if not isinstance(cookie, Cookie.BaseCookie):
  472. try:
  473. c = SimpleCookie()
  474. c.load(cookie)
  475. except Cookie.CookieError:
  476. # Invalid cookie
  477. return {}
  478. else:
  479. c = cookie
  480. cookiedict = {}
  481. for key in c.keys():
  482. cookiedict[key] = c.get(key).value
  483. return cookiedict
  484. class BadHeaderError(ValueError):
  485. pass
  486. class HttpResponse(object):
  487. """A basic HTTP response, with content and dictionary-accessed headers."""
  488. status_code = 200
  489. def __init__(self, content='', mimetype=None, status=None,
  490. content_type=None):
  491. # _headers is a mapping of the lower-case name to the original case of
  492. # the header (required for working with legacy systems) and the header
  493. # value. Both the name of the header and its value are ASCII strings.
  494. self._headers = {}
  495. self._charset = settings.DEFAULT_CHARSET
  496. if mimetype: # For backwards compatibility.
  497. content_type = mimetype
  498. if not content_type:
  499. content_type = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE,
  500. self._charset)
  501. self.content = content
  502. self.cookies = SimpleCookie()
  503. if status:
  504. self.status_code = status
  505. self['Content-Type'] = content_type
  506. def __str__(self):
  507. """Full HTTP message, including headers."""
  508. return '\n'.join(['%s: %s' % (key, value)
  509. for key, value in self._headers.values()]) \
  510. + '\n\n' + self.content
  511. def _convert_to_ascii(self, *values):
  512. """Converts all values to ascii strings."""
  513. for value in values:
  514. if isinstance(value, unicode):
  515. try:
  516. value = value.encode('us-ascii')
  517. except UnicodeError, e:
  518. e.reason += ', HTTP response headers must be in US-ASCII format'
  519. raise
  520. else:
  521. value = str(value)
  522. if '\n' in value or '\r' in value:
  523. raise BadHeaderError("Header values can't contain newlines (got %r)" % (value))
  524. yield value
  525. def __setitem__(self, header, value):
  526. header, value = self._convert_to_ascii(header, value)
  527. self._headers[header.lower()] = (header, value)
  528. def __delitem__(self, header):
  529. try:
  530. del self._headers[header.lower()]
  531. except KeyError:
  532. pass
  533. def __getitem__(self, header):
  534. return self._headers[header.lower()][1]
  535. def __getstate__(self):
  536. # SimpleCookie is not pickeable with pickle.HIGHEST_PROTOCOL, so we
  537. # serialise to a string instead
  538. state = self.__dict__.copy()
  539. state['cookies'] = str(state['cookies'])
  540. return state
  541. def __setstate__(self, state):
  542. self.__dict__.update(state)
  543. self.cookies = SimpleCookie(self.cookies)
  544. def has_header(self, header):
  545. """Case-insensitive check for a header."""
  546. return header.lower() in self._headers
  547. __contains__ = has_header
  548. def items(self):
  549. return self._headers.values()
  550. def get(self, header, alternate=None):
  551. return self._headers.get(header.lower(), (None, alternate))[1]
  552. def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
  553. domain=None, secure=False, httponly=False):
  554. """
  555. Sets a cookie.
  556. ``expires`` can be:
  557. - a string in the correct format,
  558. - a naive ``datetime.datetime`` object in UTC,
  559. - an aware ``datetime.datetime`` object in any time zone.
  560. If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
  561. """
  562. self.cookies[key] = value
  563. if expires is not None:
  564. if isinstance(expires, datetime.datetime):
  565. if timezone.is_aware(expires):
  566. expires = timezone.make_naive(expires, timezone.utc)
  567. delta = expires - expires.utcnow()
  568. # Add one second so the date matches exactly (a fraction of
  569. # time gets lost between converting to a timedelta and
  570. # then the date string).
  571. delta = delta + datetime.timedelta(seconds=1)
  572. # Just set max_age - the max_age logic will set expires.
  573. expires = None
  574. max_age = max(0, delta.days * 86400 + delta.seconds)
  575. else:
  576. self.cookies[key]['expires'] = expires
  577. if max_age is not None:
  578. self.cookies[key]['max-age'] = max_age
  579. # IE requires expires, so set it if hasn't been already.
  580. if not expires:
  581. self.cookies[key]['expires'] = cookie_date(time.time() +
  582. max_age)
  583. if path is not None:
  584. self.cookies[key]['path'] = path
  585. if domain is not None:
  586. self.cookies[key]['domain'] = domain
  587. if secure:
  588. self.cookies[key]['secure'] = True
  589. if httponly:
  590. self.cookies[key]['httponly'] = True
  591. def set_signed_cookie(self, key, value, salt='', **kwargs):
  592. value = signing.get_cookie_signer(salt=key + salt).sign(value)
  593. return self.set_cookie(key, value, **kwargs)
  594. def delete_cookie(self, key, path='/', domain=None):
  595. self.set_cookie(key, max_age=0, path=path, domain=domain,
  596. expires='Thu, 01-Jan-1970 00:00:00 GMT')
  597. def _get_content(self):
  598. if self.has_header('Content-Encoding'):
  599. return ''.join([str(e) for e in self._container])
  600. return ''.join([smart_str(e, self._charset) for e in self._container])
  601. def _set_content(self, value):
  602. if hasattr(value, '__iter__'):
  603. self._container = value
  604. self._base_content_is_iter = True
  605. else:
  606. self._container = [value]
  607. self._base_content_is_iter = False
  608. content = property(_get_content, _set_content)
  609. def __iter__(self):
  610. self._iterator = iter(self._container)
  611. return self
  612. def next(self):
  613. chunk = self._iterator.next()
  614. if isinstance(chunk, unicode):
  615. chunk = chunk.encode(self._charset)
  616. return str(chunk)
  617. def close(self):
  618. if hasattr(self._container, 'close'):
  619. self._container.close()
  620. # The remaining methods partially implement the file-like object interface.
  621. # See http://docs.python.org/lib/bltin-file-objects.html
  622. def write(self, content):
  623. if self._base_content_is_iter:
  624. raise Exception("This %s instance is not writable" % self.__class__)
  625. self._container.append(content)
  626. def flush(self):
  627. pass
  628. def tell(self):
  629. if self._base_content_is_iter:
  630. raise Exception("This %s instance cannot tell its position" % self.__class__)
  631. return sum([len(str(chunk)) for chunk in self._container])
  632. class HttpResponseRedirectBase(HttpResponse):
  633. allowed_schemes = ['http', 'https', 'ftp']
  634. def __init__(self, redirect_to):
  635. super(HttpResponseRedirectBase, self).__init__()
  636. parsed = urlparse(redirect_to)
  637. if parsed.scheme and parsed.scheme not in self.allowed_schemes:
  638. raise SuspiciousOperation("Unsafe redirect to URL with scheme '%s'" % parsed.scheme)
  639. self['Location'] = iri_to_uri(redirect_to)
  640. class HttpResponseRedirect(HttpResponseRedirectBase):
  641. status_code = 302
  642. class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
  643. status_code = 301
  644. class HttpResponseNotModified(HttpResponse):
  645. status_code = 304
  646. class HttpResponseBadRequest(HttpResponse):
  647. status_code = 400
  648. class HttpResponseNotFound(HttpResponse):
  649. status_code = 404
  650. class HttpResponseForbidden(HttpResponse):
  651. status_code = 403
  652. class HttpResponseNotAllowed(HttpResponse):
  653. status_code = 405
  654. def __init__(self, permitted_methods):
  655. super(HttpResponseNotAllowed, self).__init__()
  656. self['Allow'] = ', '.join(permitted_methods)
  657. class HttpResponseGone(HttpResponse):
  658. status_code = 410
  659. class HttpResponseServerError(HttpResponse):
  660. status_code = 500
  661. # A backwards compatible alias for HttpRequest.get_host.
  662. def get_host(request):
  663. return request.get_host()
  664. # It's neither necessary nor appropriate to use
  665. # django.utils.encoding.smart_unicode for parsing URLs and form inputs. Thus,
  666. # this slightly more restricted function.
  667. def str_to_unicode(s, encoding):
  668. """
  669. Converts basestring objects to unicode, using the given encoding. Illegally
  670. encoded input characters are replaced with Unicode "unknown" codepoint
  671. (\ufffd).
  672. Returns any non-basestring objects without change.
  673. """
  674. if isinstance(s, str):
  675. return unicode(s, encoding, 'replace')
  676. else:
  677. return s
  678. def validate_host(host, allowed_hosts):
  679. """
  680. Validate the given host header value for this site.
  681. Check that the host looks valid and matches a host or host pattern in the
  682. given list of ``allowed_hosts``. Any pattern beginning with a period
  683. matches a domain and all its subdomains (e.g. ``.example.com`` matches
  684. ``example.com`` and any subdomain), ``*`` matches anything, and anything
  685. else must match exactly.
  686. Return ``True`` for a valid host, ``False`` otherwise.
  687. """
  688. # All validation is case-insensitive
  689. host = host.lower()
  690. # Basic sanity check
  691. if not host_validation_re.match(host):
  692. return False
  693. # Validate only the domain part.
  694. if host[-1] == ']':
  695. # It's an IPv6 address without a port.
  696. domain = host
  697. else:
  698. domain = host.rsplit(':', 1)[0]
  699. for pattern in allowed_hosts:
  700. pattern = pattern.lower()
  701. match = (
  702. pattern == '*' or
  703. pattern.startswith('.') and (
  704. domain.endswith(pattern) or domain == pattern[1:]
  705. ) or
  706. pattern == domain
  707. )
  708. if match:
  709. return True
  710. return False