PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/Django-1.4.3/django/http/__init__.py

https://bitbucket.org/ducopdep/tiny_blog
Python | 801 lines | 758 code | 16 blank | 27 comment | 25 complexity | 5e647b82664dc9013c5f9c84a136d454 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. # Disallow potentially poisoned hostnames.
  190. if not host_validation_re.match(host.lower()):
  191. raise SuspiciousOperation('Invalid HTTP_HOST header: %s' % host)
  192. return host
  193. def get_full_path(self):
  194. # RFC 3986 requires query string arguments to be in the ASCII range.
  195. # Rather than crash if this doesn't happen, we encode defensively.
  196. return '%s%s' % (self.path, self.META.get('QUERY_STRING', '') and ('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) or '')
  197. def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
  198. """
  199. Attempts to return a signed cookie. If the signature fails or the
  200. cookie has expired, raises an exception... unless you provide the
  201. default argument in which case that value will be returned instead.
  202. """
  203. try:
  204. cookie_value = self.COOKIES[key].encode('utf-8')
  205. except KeyError:
  206. if default is not RAISE_ERROR:
  207. return default
  208. else:
  209. raise
  210. try:
  211. value = signing.get_cookie_signer(salt=key + salt).unsign(
  212. cookie_value, max_age=max_age)
  213. except signing.BadSignature:
  214. if default is not RAISE_ERROR:
  215. return default
  216. else:
  217. raise
  218. return value
  219. def build_absolute_uri(self, location=None):
  220. """
  221. Builds an absolute URI from the location and the variables available in
  222. this request. If no location is specified, the absolute URI is built on
  223. ``request.get_full_path()``.
  224. """
  225. if not location:
  226. location = self.get_full_path()
  227. if not absolute_http_url_re.match(location):
  228. current_uri = '%s://%s%s' % (self.is_secure() and 'https' or 'http',
  229. self.get_host(), self.path)
  230. location = urljoin(current_uri, location)
  231. return iri_to_uri(location)
  232. def _is_secure(self):
  233. return os.environ.get("HTTPS") == "on"
  234. def is_secure(self):
  235. # First, check the SECURE_PROXY_SSL_HEADER setting.
  236. if settings.SECURE_PROXY_SSL_HEADER:
  237. try:
  238. header, value = settings.SECURE_PROXY_SSL_HEADER
  239. except ValueError:
  240. raise ImproperlyConfigured('The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.')
  241. if self.META.get(header, None) == value:
  242. return True
  243. # Failing that, fall back to _is_secure(), which is a hook for
  244. # subclasses to implement.
  245. return self._is_secure()
  246. def is_ajax(self):
  247. return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
  248. def _set_encoding(self, val):
  249. """
  250. Sets the encoding used for GET/POST accesses. If the GET or POST
  251. dictionary has already been created, it is removed and recreated on the
  252. next access (so that it is decoded correctly).
  253. """
  254. self._encoding = val
  255. if hasattr(self, '_get'):
  256. del self._get
  257. if hasattr(self, '_post'):
  258. del self._post
  259. def _get_encoding(self):
  260. return self._encoding
  261. encoding = property(_get_encoding, _set_encoding)
  262. def _initialize_handlers(self):
  263. self._upload_handlers = [uploadhandler.load_handler(handler, self)
  264. for handler in settings.FILE_UPLOAD_HANDLERS]
  265. def _set_upload_handlers(self, upload_handlers):
  266. if hasattr(self, '_files'):
  267. raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
  268. self._upload_handlers = upload_handlers
  269. def _get_upload_handlers(self):
  270. if not self._upload_handlers:
  271. # If there are no upload handlers defined, initialize them from settings.
  272. self._initialize_handlers()
  273. return self._upload_handlers
  274. upload_handlers = property(_get_upload_handlers, _set_upload_handlers)
  275. def parse_file_upload(self, META, post_data):
  276. """Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
  277. self.upload_handlers = ImmutableList(
  278. self.upload_handlers,
  279. warning = "You cannot alter upload handlers after the upload has been processed."
  280. )
  281. parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
  282. return parser.parse()
  283. @property
  284. def body(self):
  285. if not hasattr(self, '_body'):
  286. if self._read_started:
  287. raise Exception("You cannot access body after reading from request's data stream")
  288. try:
  289. self._body = self.read()
  290. except IOError, e:
  291. raise UnreadablePostError, e, sys.exc_traceback
  292. self._stream = StringIO(self._body)
  293. return self._body
  294. @property
  295. def raw_post_data(self):
  296. warnings.warn('HttpRequest.raw_post_data has been deprecated. Use HttpRequest.body instead.', PendingDeprecationWarning)
  297. return self.body
  298. def _mark_post_parse_error(self):
  299. self._post = QueryDict('')
  300. self._files = MultiValueDict()
  301. self._post_parse_error = True
  302. def _load_post_and_files(self):
  303. # Populates self._post and self._files
  304. if self.method != 'POST':
  305. self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()
  306. return
  307. if self._read_started and not hasattr(self, '_body'):
  308. self._mark_post_parse_error()
  309. return
  310. if self.META.get('CONTENT_TYPE', '').startswith('multipart'):
  311. if hasattr(self, '_body'):
  312. # Use already read data
  313. data = StringIO(self._body)
  314. else:
  315. data = self
  316. try:
  317. self._post, self._files = self.parse_file_upload(self.META, data)
  318. except:
  319. # An error occured while parsing POST data. Since when
  320. # formatting the error the request handler might access
  321. # self.POST, set self._post and self._file to prevent
  322. # attempts to parse POST data again.
  323. # Mark that an error occured. This allows self.__repr__ to
  324. # be explicit about it instead of simply representing an
  325. # empty POST
  326. self._mark_post_parse_error()
  327. raise
  328. else:
  329. self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
  330. ## File-like and iterator interface.
  331. ##
  332. ## Expects self._stream to be set to an appropriate source of bytes by
  333. ## a corresponding request subclass (WSGIRequest or ModPythonRequest).
  334. ## Also when request data has already been read by request.POST or
  335. ## request.body, self._stream points to a StringIO instance
  336. ## containing that data.
  337. def read(self, *args, **kwargs):
  338. self._read_started = True
  339. return self._stream.read(*args, **kwargs)
  340. def readline(self, *args, **kwargs):
  341. self._read_started = True
  342. return self._stream.readline(*args, **kwargs)
  343. def xreadlines(self):
  344. while True:
  345. buf = self.readline()
  346. if not buf:
  347. break
  348. yield buf
  349. __iter__ = xreadlines
  350. def readlines(self):
  351. return list(iter(self))
  352. class QueryDict(MultiValueDict):
  353. """
  354. A specialized MultiValueDict that takes a query string when initialized.
  355. This is immutable unless you create a copy of it.
  356. Values retrieved from this class are converted from the given encoding
  357. (DEFAULT_CHARSET by default) to unicode.
  358. """
  359. # These are both reset in __init__, but is specified here at the class
  360. # level so that unpickling will have valid values
  361. _mutable = True
  362. _encoding = None
  363. def __init__(self, query_string, mutable=False, encoding=None):
  364. MultiValueDict.__init__(self)
  365. if not encoding:
  366. encoding = settings.DEFAULT_CHARSET
  367. self.encoding = encoding
  368. for key, value in parse_qsl((query_string or ''), True): # keep_blank_values=True
  369. self.appendlist(force_unicode(key, encoding, errors='replace'),
  370. force_unicode(value, encoding, errors='replace'))
  371. self._mutable = mutable
  372. def _get_encoding(self):
  373. if self._encoding is None:
  374. self._encoding = settings.DEFAULT_CHARSET
  375. return self._encoding
  376. def _set_encoding(self, value):
  377. self._encoding = value
  378. encoding = property(_get_encoding, _set_encoding)
  379. def _assert_mutable(self):
  380. if not self._mutable:
  381. raise AttributeError("This QueryDict instance is immutable")
  382. def __setitem__(self, key, value):
  383. self._assert_mutable()
  384. key = str_to_unicode(key, self.encoding)
  385. value = str_to_unicode(value, self.encoding)
  386. MultiValueDict.__setitem__(self, key, value)
  387. def __delitem__(self, key):
  388. self._assert_mutable()
  389. super(QueryDict, self).__delitem__(key)
  390. def __copy__(self):
  391. result = self.__class__('', mutable=True, encoding=self.encoding)
  392. for key, value in dict.items(self):
  393. dict.__setitem__(result, key, value)
  394. return result
  395. def __deepcopy__(self, memo):
  396. import copy
  397. result = self.__class__('', mutable=True, encoding=self.encoding)
  398. memo[id(self)] = result
  399. for key, value in dict.items(self):
  400. dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo))
  401. return result
  402. def setlist(self, key, list_):
  403. self._assert_mutable()
  404. key = str_to_unicode(key, self.encoding)
  405. list_ = [str_to_unicode(elt, self.encoding) for elt in list_]
  406. MultiValueDict.setlist(self, key, list_)
  407. def setlistdefault(self, key, default_list=()):
  408. self._assert_mutable()
  409. if key not in self:
  410. self.setlist(key, default_list)
  411. return MultiValueDict.getlist(self, key)
  412. def appendlist(self, key, value):
  413. self._assert_mutable()
  414. key = str_to_unicode(key, self.encoding)
  415. value = str_to_unicode(value, self.encoding)
  416. MultiValueDict.appendlist(self, key, value)
  417. def update(self, other_dict):
  418. self._assert_mutable()
  419. f = lambda s: str_to_unicode(s, self.encoding)
  420. if hasattr(other_dict, 'lists'):
  421. for key, valuelist in other_dict.lists():
  422. for value in valuelist:
  423. MultiValueDict.update(self, {f(key): f(value)})
  424. else:
  425. d = dict([(f(k), f(v)) for k, v in other_dict.items()])
  426. MultiValueDict.update(self, d)
  427. def pop(self, key, *args):
  428. self._assert_mutable()
  429. return MultiValueDict.pop(self, key, *args)
  430. def popitem(self):
  431. self._assert_mutable()
  432. return MultiValueDict.popitem(self)
  433. def clear(self):
  434. self._assert_mutable()
  435. MultiValueDict.clear(self)
  436. def setdefault(self, key, default=None):
  437. self._assert_mutable()
  438. key = str_to_unicode(key, self.encoding)
  439. default = str_to_unicode(default, self.encoding)
  440. return MultiValueDict.setdefault(self, key, default)
  441. def copy(self):
  442. """Returns a mutable copy of this object."""
  443. return self.__deepcopy__({})
  444. def urlencode(self, safe=None):
  445. """
  446. Returns an encoded string of all query string arguments.
  447. :arg safe: Used to specify characters which do not require quoting, for
  448. example::
  449. >>> q = QueryDict('', mutable=True)
  450. >>> q['next'] = '/a&b/'
  451. >>> q.urlencode()
  452. 'next=%2Fa%26b%2F'
  453. >>> q.urlencode(safe='/')
  454. 'next=/a%26b/'
  455. """
  456. output = []
  457. if safe:
  458. encode = lambda k, v: '%s=%s' % ((quote(k, safe), quote(v, safe)))
  459. else:
  460. encode = lambda k, v: urlencode({k: v})
  461. for k, list_ in self.lists():
  462. k = smart_str(k, self.encoding)
  463. output.extend([encode(k, smart_str(v, self.encoding))
  464. for v in list_])
  465. return '&'.join(output)
  466. def parse_cookie(cookie):
  467. if cookie == '':
  468. return {}
  469. if not isinstance(cookie, Cookie.BaseCookie):
  470. try:
  471. c = SimpleCookie()
  472. c.load(cookie)
  473. except Cookie.CookieError:
  474. # Invalid cookie
  475. return {}
  476. else:
  477. c = cookie
  478. cookiedict = {}
  479. for key in c.keys():
  480. cookiedict[key] = c.get(key).value
  481. return cookiedict
  482. class BadHeaderError(ValueError):
  483. pass
  484. class HttpResponse(object):
  485. """A basic HTTP response, with content and dictionary-accessed headers."""
  486. status_code = 200
  487. def __init__(self, content='', mimetype=None, status=None,
  488. content_type=None):
  489. # _headers is a mapping of the lower-case name to the original case of
  490. # the header (required for working with legacy systems) and the header
  491. # value. Both the name of the header and its value are ASCII strings.
  492. self._headers = {}
  493. self._charset = settings.DEFAULT_CHARSET
  494. if mimetype: # For backwards compatibility.
  495. content_type = mimetype
  496. if not content_type:
  497. content_type = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE,
  498. self._charset)
  499. self.content = content
  500. self.cookies = SimpleCookie()
  501. if status:
  502. self.status_code = status
  503. self['Content-Type'] = content_type
  504. def __str__(self):
  505. """Full HTTP message, including headers."""
  506. return '\n'.join(['%s: %s' % (key, value)
  507. for key, value in self._headers.values()]) \
  508. + '\n\n' + self.content
  509. def _convert_to_ascii(self, *values):
  510. """Converts all values to ascii strings."""
  511. for value in values:
  512. if isinstance(value, unicode):
  513. try:
  514. value = value.encode('us-ascii')
  515. except UnicodeError, e:
  516. e.reason += ', HTTP response headers must be in US-ASCII format'
  517. raise
  518. else:
  519. value = str(value)
  520. if '\n' in value or '\r' in value:
  521. raise BadHeaderError("Header values can't contain newlines (got %r)" % (value))
  522. yield value
  523. def __setitem__(self, header, value):
  524. header, value = self._convert_to_ascii(header, value)
  525. self._headers[header.lower()] = (header, value)
  526. def __delitem__(self, header):
  527. try:
  528. del self._headers[header.lower()]
  529. except KeyError:
  530. pass
  531. def __getitem__(self, header):
  532. return self._headers[header.lower()][1]
  533. def __getstate__(self):
  534. # SimpleCookie is not pickeable with pickle.HIGHEST_PROTOCOL, so we
  535. # serialise to a string instead
  536. state = self.__dict__.copy()
  537. state['cookies'] = str(state['cookies'])
  538. return state
  539. def __setstate__(self, state):
  540. self.__dict__.update(state)
  541. self.cookies = SimpleCookie(self.cookies)
  542. def has_header(self, header):
  543. """Case-insensitive check for a header."""
  544. return header.lower() in self._headers
  545. __contains__ = has_header
  546. def items(self):
  547. return self._headers.values()
  548. def get(self, header, alternate=None):
  549. return self._headers.get(header.lower(), (None, alternate))[1]
  550. def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
  551. domain=None, secure=False, httponly=False):
  552. """
  553. Sets a cookie.
  554. ``expires`` can be:
  555. - a string in the correct format,
  556. - a naive ``datetime.datetime`` object in UTC,
  557. - an aware ``datetime.datetime`` object in any time zone.
  558. If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
  559. """
  560. self.cookies[key] = value
  561. if expires is not None:
  562. if isinstance(expires, datetime.datetime):
  563. if timezone.is_aware(expires):
  564. expires = timezone.make_naive(expires, timezone.utc)
  565. delta = expires - expires.utcnow()
  566. # Add one second so the date matches exactly (a fraction of
  567. # time gets lost between converting to a timedelta and
  568. # then the date string).
  569. delta = delta + datetime.timedelta(seconds=1)
  570. # Just set max_age - the max_age logic will set expires.
  571. expires = None
  572. max_age = max(0, delta.days * 86400 + delta.seconds)
  573. else:
  574. self.cookies[key]['expires'] = expires
  575. if max_age is not None:
  576. self.cookies[key]['max-age'] = max_age
  577. # IE requires expires, so set it if hasn't been already.
  578. if not expires:
  579. self.cookies[key]['expires'] = cookie_date(time.time() +
  580. max_age)
  581. if path is not None:
  582. self.cookies[key]['path'] = path
  583. if domain is not None:
  584. self.cookies[key]['domain'] = domain
  585. if secure:
  586. self.cookies[key]['secure'] = True
  587. if httponly:
  588. self.cookies[key]['httponly'] = True
  589. def set_signed_cookie(self, key, value, salt='', **kwargs):
  590. value = signing.get_cookie_signer(salt=key + salt).sign(value)
  591. return self.set_cookie(key, value, **kwargs)
  592. def delete_cookie(self, key, path='/', domain=None):
  593. self.set_cookie(key, max_age=0, path=path, domain=domain,
  594. expires='Thu, 01-Jan-1970 00:00:00 GMT')
  595. def _get_content(self):
  596. if self.has_header('Content-Encoding'):
  597. return ''.join([str(e) for e in self._container])
  598. return ''.join([smart_str(e, self._charset) for e in self._container])
  599. def _set_content(self, value):
  600. if hasattr(value, '__iter__'):
  601. self._container = value
  602. self._base_content_is_iter = True
  603. else:
  604. self._container = [value]
  605. self._base_content_is_iter = False
  606. content = property(_get_content, _set_content)
  607. def __iter__(self):
  608. self._iterator = iter(self._container)
  609. return self
  610. def next(self):
  611. chunk = self._iterator.next()
  612. if isinstance(chunk, unicode):
  613. chunk = chunk.encode(self._charset)
  614. return str(chunk)
  615. def close(self):
  616. if hasattr(self._container, 'close'):
  617. self._container.close()
  618. # The remaining methods partially implement the file-like object interface.
  619. # See http://docs.python.org/lib/bltin-file-objects.html
  620. def write(self, content):
  621. if self._base_content_is_iter:
  622. raise Exception("This %s instance is not writable" % self.__class__)
  623. self._container.append(content)
  624. def flush(self):
  625. pass
  626. def tell(self):
  627. if self._base_content_is_iter:
  628. raise Exception("This %s instance cannot tell its position" % self.__class__)
  629. return sum([len(str(chunk)) for chunk in self._container])
  630. class HttpResponseRedirectBase(HttpResponse):
  631. allowed_schemes = ['http', 'https', 'ftp']
  632. def __init__(self, redirect_to):
  633. super(HttpResponseRedirectBase, self).__init__()
  634. parsed = urlparse(redirect_to)
  635. if parsed.scheme and parsed.scheme not in self.allowed_schemes:
  636. raise SuspiciousOperation("Unsafe redirect to URL with scheme '%s'" % parsed.scheme)
  637. self['Location'] = iri_to_uri(redirect_to)
  638. class HttpResponseRedirect(HttpResponseRedirectBase):
  639. status_code = 302
  640. class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
  641. status_code = 301
  642. class HttpResponseNotModified(HttpResponse):
  643. status_code = 304
  644. class HttpResponseBadRequest(HttpResponse):
  645. status_code = 400
  646. class HttpResponseNotFound(HttpResponse):
  647. status_code = 404
  648. class HttpResponseForbidden(HttpResponse):
  649. status_code = 403
  650. class HttpResponseNotAllowed(HttpResponse):
  651. status_code = 405
  652. def __init__(self, permitted_methods):
  653. super(HttpResponseNotAllowed, self).__init__()
  654. self['Allow'] = ', '.join(permitted_methods)
  655. class HttpResponseGone(HttpResponse):
  656. status_code = 410
  657. class HttpResponseServerError(HttpResponse):
  658. status_code = 500
  659. # A backwards compatible alias for HttpRequest.get_host.
  660. def get_host(request):
  661. return request.get_host()
  662. # It's neither necessary nor appropriate to use
  663. # django.utils.encoding.smart_unicode for parsing URLs and form inputs. Thus,
  664. # this slightly more restricted function.
  665. def str_to_unicode(s, encoding):
  666. """
  667. Converts basestring objects to unicode, using the given encoding. Illegally
  668. encoded input characters are replaced with Unicode "unknown" codepoint
  669. (\ufffd).
  670. Returns any non-basestring objects without change.
  671. """
  672. if isinstance(s, str):
  673. return unicode(s, encoding, 'replace')
  674. else:
  675. return s