2012-06-08 00:08:47 +08:00
|
|
|
from __future__ import absolute_import, unicode_literals
|
2011-10-18 08:47:49 +08:00
|
|
|
|
2010-09-13 04:52:49 +08:00
|
|
|
import datetime
|
2006-07-22 00:20:22 +08:00
|
|
|
import os
|
2008-08-24 01:28:12 +08:00
|
|
|
import re
|
2012-02-11 06:51:07 +08:00
|
|
|
import sys
|
2010-09-13 04:52:49 +08:00
|
|
|
import time
|
2011-12-17 07:40:32 +08:00
|
|
|
import warnings
|
|
|
|
|
2012-05-06 01:47:03 +08:00
|
|
|
from io import BytesIO
|
2005-07-13 09:25:57 +08:00
|
|
|
from pprint import pformat
|
2010-12-02 06:25:17 +08:00
|
|
|
from urllib import urlencode, quote
|
2012-03-31 18:34:11 +08:00
|
|
|
from urlparse import urljoin, parse_qsl
|
2008-03-08 11:46:33 +08:00
|
|
|
|
2011-01-25 04:35:46 +08:00
|
|
|
import Cookie
|
|
|
|
# Some versions of Python 2.7 and later won't need this encoding bug fix:
|
|
|
|
_cookie_encodes_correctly = Cookie.SimpleCookie().value_encode(';') == (';', '"\\073"')
|
2011-02-13 10:24:05 +08:00
|
|
|
# See ticket #13007, http://bugs.python.org/issue2193 and http://trac.edgewall.org/ticket/2256
|
|
|
|
_tc = Cookie.SimpleCookie()
|
2011-06-29 23:12:48 +08:00
|
|
|
try:
|
2012-05-19 23:43:34 +08:00
|
|
|
_tc.load(b'foo:bar=1')
|
2011-06-29 23:12:48 +08:00
|
|
|
_cookie_allows_colon_in_names = True
|
|
|
|
except Cookie.CookieError:
|
|
|
|
_cookie_allows_colon_in_names = False
|
2011-01-25 04:35:46 +08:00
|
|
|
|
2012-03-31 16:24:29 +08:00
|
|
|
if _cookie_encodes_correctly and _cookie_allows_colon_in_names:
|
2010-11-26 21:30:50 +08:00
|
|
|
SimpleCookie = Cookie.SimpleCookie
|
|
|
|
else:
|
2012-03-31 16:24:29 +08:00
|
|
|
Morsel = Cookie.Morsel
|
2010-11-26 21:30:50 +08:00
|
|
|
|
|
|
|
class SimpleCookie(Cookie.SimpleCookie):
|
2011-01-25 04:35:46 +08:00
|
|
|
if not _cookie_encodes_correctly:
|
|
|
|
def value_encode(self, val):
|
|
|
|
# Some browsers do not support quoted-string from RFC 2109,
|
|
|
|
# including some versions of Safari and Internet Explorer.
|
|
|
|
# These browsers split on ';', and some versions of Safari
|
|
|
|
# are known to split on ', '. Therefore, we encode ';' and ','
|
|
|
|
|
|
|
|
# SimpleCookie already does the hard work of encoding and decoding.
|
|
|
|
# It uses octal sequences like '\\012' for newline etc.
|
2011-12-17 10:40:35 +08:00
|
|
|
# and non-ASCII chars. We just make use of this mechanism, to
|
2011-01-25 04:35:46 +08:00
|
|
|
# avoid introducing two encoding schemes which would be confusing
|
|
|
|
# and especially awkward for javascript.
|
|
|
|
|
|
|
|
# NB, contrary to Python docs, value_encode returns a tuple containing
|
|
|
|
# (real val, encoded_val)
|
|
|
|
val, encoded = super(SimpleCookie, self).value_encode(val)
|
|
|
|
|
|
|
|
encoded = encoded.replace(";", "\\073").replace(",","\\054")
|
|
|
|
# If encoded now contains any quoted chars, we need double quotes
|
|
|
|
# around the whole string.
|
|
|
|
if "\\" in encoded and not encoded.startswith('"'):
|
|
|
|
encoded = '"' + encoded + '"'
|
|
|
|
|
|
|
|
return val, encoded
|
2010-11-26 21:30:50 +08:00
|
|
|
|
2012-03-31 16:24:29 +08:00
|
|
|
if not _cookie_allows_colon_in_names:
|
2011-06-29 23:12:48 +08:00
|
|
|
def load(self, rawdata):
|
|
|
|
self.bad_cookies = set()
|
2012-06-08 00:08:47 +08:00
|
|
|
super(SimpleCookie, self).load(smart_str(rawdata))
|
2011-06-29 23:12:48 +08:00
|
|
|
for key in self.bad_cookies:
|
|
|
|
del self[key]
|
2011-02-13 10:24:05 +08:00
|
|
|
|
2011-06-29 23:12:48 +08:00
|
|
|
# override private __set() method:
|
2011-07-08 20:07:54 +08:00
|
|
|
# (needed for using our Morsel, and for laxness with CookieError
|
2011-06-29 23:12:48 +08:00
|
|
|
def _BaseCookie__set(self, key, real_value, coded_value):
|
2012-06-08 00:08:47 +08:00
|
|
|
key = smart_str(key)
|
2011-02-13 10:24:05 +08:00
|
|
|
try:
|
2011-07-08 20:07:54 +08:00
|
|
|
M = self.get(key, Morsel())
|
|
|
|
M.set(key, real_value, coded_value)
|
|
|
|
dict.__setitem__(self, key, M)
|
2011-02-13 10:24:05 +08:00
|
|
|
except Cookie.CookieError:
|
2011-06-26 00:18:40 +08:00
|
|
|
self.bad_cookies.add(key)
|
|
|
|
dict.__setitem__(self, key, Cookie.Morsel())
|
2011-02-13 10:24:05 +08:00
|
|
|
|
|
|
|
|
2008-07-01 23:10:51 +08:00
|
|
|
from django.conf import settings
|
2011-05-21 22:41:14 +08:00
|
|
|
from django.core import signing
|
2011-12-17 06:06:06 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2008-07-01 23:10:51 +08:00
|
|
|
from django.core.files import uploadhandler
|
2011-10-18 08:47:49 +08:00
|
|
|
from django.http.multipartparser import MultiPartParser
|
|
|
|
from django.http.utils import *
|
|
|
|
from django.utils.datastructures import MultiValueDict, ImmutableList
|
|
|
|
from django.utils.encoding import smart_str, iri_to_uri, force_unicode
|
|
|
|
from django.utils.http import cookie_date
|
2012-03-19 04:58:22 +08:00
|
|
|
from django.utils import timezone
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-06-20 12:06:16 +08:00
|
|
|
RESERVED_CHARS="!*'();:@&=+$,/?%#[]"
|
|
|
|
|
2008-08-24 01:28:12 +08:00
|
|
|
absolute_http_url_re = re.compile(r"^https?://", re.I)
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Http404(Exception):
|
|
|
|
pass
|
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
RAISE_ERROR = object()
|
|
|
|
|
2011-06-10 07:15:42 +08:00
|
|
|
|
|
|
|
def build_request_repr(request, path_override=None, GET_override=None,
|
|
|
|
POST_override=None, COOKIES_override=None,
|
|
|
|
META_override=None):
|
|
|
|
"""
|
|
|
|
Builds and returns the request's representation string. The request's
|
|
|
|
attributes may be overridden by pre-processed values.
|
|
|
|
"""
|
|
|
|
# Since this is called as part of error handling, we need to be very
|
|
|
|
# robust against potentially malformed input.
|
|
|
|
try:
|
|
|
|
get = (pformat(GET_override)
|
|
|
|
if GET_override is not None
|
|
|
|
else pformat(request.GET))
|
|
|
|
except:
|
|
|
|
get = '<could not parse>'
|
|
|
|
if request._post_parse_error:
|
|
|
|
post = '<could not parse>'
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
post = (pformat(POST_override)
|
|
|
|
if POST_override is not None
|
|
|
|
else pformat(request.POST))
|
|
|
|
except:
|
|
|
|
post = '<could not parse>'
|
|
|
|
try:
|
|
|
|
cookies = (pformat(COOKIES_override)
|
|
|
|
if COOKIES_override is not None
|
|
|
|
else pformat(request.COOKIES))
|
|
|
|
except:
|
|
|
|
cookies = '<could not parse>'
|
|
|
|
try:
|
|
|
|
meta = (pformat(META_override)
|
|
|
|
if META_override is not None
|
|
|
|
else pformat(request.META))
|
|
|
|
except:
|
|
|
|
meta = '<could not parse>'
|
|
|
|
path = path_override if path_override is not None else request.path
|
2012-06-08 00:08:47 +08:00
|
|
|
return smart_str('<%s\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' %
|
2011-06-10 07:15:42 +08:00
|
|
|
(request.__class__.__name__,
|
|
|
|
path,
|
|
|
|
unicode(get),
|
|
|
|
unicode(post),
|
|
|
|
unicode(cookies),
|
|
|
|
unicode(meta)))
|
|
|
|
|
2012-02-11 06:51:07 +08:00
|
|
|
class UnreadablePostError(IOError):
|
|
|
|
pass
|
2011-06-10 07:15:42 +08:00
|
|
|
|
2006-06-20 11:48:31 +08:00
|
|
|
class HttpRequest(object):
|
2008-03-08 11:46:33 +08:00
|
|
|
"""A basic HTTP request."""
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
|
|
|
# The encoding used in GET/POST dicts. None means use default setting.
|
|
|
|
_encoding = None
|
2008-07-01 23:10:51 +08:00
|
|
|
_upload_handlers = []
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def __init__(self):
|
|
|
|
self.GET, self.POST, self.COOKIES, self.META, self.FILES = {}, {}, {}, {}, {}
|
|
|
|
self.path = ''
|
2008-07-21 15:57:10 +08:00
|
|
|
self.path_info = ''
|
2006-06-20 11:48:31 +08:00
|
|
|
self.method = None
|
2011-06-10 07:15:42 +08:00
|
|
|
self._post_parse_error = False
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
2011-06-10 07:15:42 +08:00
|
|
|
return build_request_repr(self)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2007-09-16 01:46:03 +08:00
|
|
|
def get_host(self):
|
2008-03-08 11:46:33 +08:00
|
|
|
"""Returns the HTTP host using the environment or request headers."""
|
2007-09-16 01:46:03 +08:00
|
|
|
# We try three options, in order of decreasing preference.
|
2011-09-10 08:46:38 +08:00
|
|
|
if settings.USE_X_FORWARDED_HOST and (
|
|
|
|
'HTTP_X_FORWARDED_HOST' in self.META):
|
2007-10-04 06:21:43 +08:00
|
|
|
host = self.META['HTTP_X_FORWARDED_HOST']
|
|
|
|
elif 'HTTP_HOST' in self.META:
|
2007-09-16 01:46:03 +08:00
|
|
|
host = self.META['HTTP_HOST']
|
|
|
|
else:
|
|
|
|
# Reconstruct the host using the algorithm from PEP 333.
|
|
|
|
host = self.META['SERVER_NAME']
|
2008-08-29 00:18:32 +08:00
|
|
|
server_port = str(self.META['SERVER_PORT'])
|
|
|
|
if server_port != (self.is_secure() and '443' or '80'):
|
2007-09-16 01:46:03 +08:00
|
|
|
host = '%s:%s' % (host, server_port)
|
|
|
|
return host
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def get_full_path(self):
|
2011-03-02 20:47:36 +08:00
|
|
|
# RFC 3986 requires query string arguments to be in the ASCII range.
|
|
|
|
# Rather than crash if this doesn't happen, we encode defensively.
|
|
|
|
return '%s%s' % (self.path, self.META.get('QUERY_STRING', '') and ('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) or '')
|
2006-08-09 23:40:24 +08:00
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
|
|
|
|
"""
|
|
|
|
Attempts to return a signed cookie. If the signature fails or the
|
|
|
|
cookie has expired, raises an exception... unless you provide the
|
|
|
|
default argument in which case that value will be returned instead.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
cookie_value = self.COOKIES[key].encode('utf-8')
|
|
|
|
except KeyError:
|
|
|
|
if default is not RAISE_ERROR:
|
|
|
|
return default
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
try:
|
|
|
|
value = signing.get_cookie_signer(salt=key + salt).unsign(
|
|
|
|
cookie_value, max_age=max_age)
|
|
|
|
except signing.BadSignature:
|
|
|
|
if default is not RAISE_ERROR:
|
|
|
|
return default
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
return value
|
|
|
|
|
2007-09-14 13:28:00 +08:00
|
|
|
def build_absolute_uri(self, location=None):
|
|
|
|
"""
|
|
|
|
Builds an absolute URI from the location and the variables available in
|
|
|
|
this request. If no location is specified, the absolute URI is built on
|
|
|
|
``request.get_full_path()``.
|
|
|
|
"""
|
|
|
|
if not location:
|
2007-09-14 13:39:59 +08:00
|
|
|
location = self.get_full_path()
|
2008-08-24 01:28:12 +08:00
|
|
|
if not absolute_http_url_re.match(location):
|
2007-09-14 13:28:00 +08:00
|
|
|
current_uri = '%s://%s%s' % (self.is_secure() and 'https' or 'http',
|
2007-09-16 01:46:03 +08:00
|
|
|
self.get_host(), self.path)
|
2007-09-14 13:28:00 +08:00
|
|
|
location = urljoin(current_uri, location)
|
2009-04-12 11:50:47 +08:00
|
|
|
return iri_to_uri(location)
|
2007-09-14 13:28:00 +08:00
|
|
|
|
2011-12-17 06:06:06 +08:00
|
|
|
def _is_secure(self):
|
2006-07-22 00:20:22 +08:00
|
|
|
return os.environ.get("HTTPS") == "on"
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2011-12-17 06:06:06 +08:00
|
|
|
def is_secure(self):
|
|
|
|
# First, check the SECURE_PROXY_SSL_HEADER setting.
|
|
|
|
if settings.SECURE_PROXY_SSL_HEADER:
|
|
|
|
try:
|
|
|
|
header, value = settings.SECURE_PROXY_SSL_HEADER
|
|
|
|
except ValueError:
|
|
|
|
raise ImproperlyConfigured('The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.')
|
|
|
|
if self.META.get(header, None) == value:
|
|
|
|
return True
|
|
|
|
|
|
|
|
# Failing that, fall back to _is_secure(), which is a hook for
|
|
|
|
# subclasses to implement.
|
|
|
|
return self._is_secure()
|
|
|
|
|
2008-03-20 15:16:16 +08:00
|
|
|
def is_ajax(self):
|
|
|
|
return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
|
|
|
|
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
def _set_encoding(self, val):
|
|
|
|
"""
|
|
|
|
Sets the encoding used for GET/POST accesses. If the GET or POST
|
|
|
|
dictionary has already been created, it is removed and recreated on the
|
|
|
|
next access (so that it is decoded correctly).
|
|
|
|
"""
|
|
|
|
self._encoding = val
|
|
|
|
if hasattr(self, '_get'):
|
|
|
|
del self._get
|
|
|
|
if hasattr(self, '_post'):
|
|
|
|
del self._post
|
|
|
|
|
|
|
|
def _get_encoding(self):
|
|
|
|
return self._encoding
|
|
|
|
|
|
|
|
encoding = property(_get_encoding, _set_encoding)
|
|
|
|
|
2008-07-01 23:10:51 +08:00
|
|
|
def _initialize_handlers(self):
|
|
|
|
self._upload_handlers = [uploadhandler.load_handler(handler, self)
|
|
|
|
for handler in settings.FILE_UPLOAD_HANDLERS]
|
|
|
|
|
|
|
|
def _set_upload_handlers(self, upload_handlers):
|
|
|
|
if hasattr(self, '_files'):
|
|
|
|
raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
|
|
|
|
self._upload_handlers = upload_handlers
|
|
|
|
|
|
|
|
def _get_upload_handlers(self):
|
|
|
|
if not self._upload_handlers:
|
2011-08-12 22:14:15 +08:00
|
|
|
# If there are no upload handlers defined, initialize them from settings.
|
2008-07-01 23:10:51 +08:00
|
|
|
self._initialize_handlers()
|
|
|
|
return self._upload_handlers
|
|
|
|
|
|
|
|
upload_handlers = property(_get_upload_handlers, _set_upload_handlers)
|
|
|
|
|
|
|
|
def parse_file_upload(self, META, post_data):
|
|
|
|
"""Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
|
|
|
|
self.upload_handlers = ImmutableList(
|
|
|
|
self.upload_handlers,
|
|
|
|
warning = "You cannot alter upload handlers after the upload has been processed."
|
|
|
|
)
|
|
|
|
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
|
|
|
|
return parser.parse()
|
2008-03-08 11:46:33 +08:00
|
|
|
|
2011-12-17 07:40:32 +08:00
|
|
|
@property
|
|
|
|
def body(self):
|
|
|
|
if not hasattr(self, '_body'):
|
2010-10-30 00:39:25 +08:00
|
|
|
if self._read_started:
|
2011-12-17 07:40:32 +08:00
|
|
|
raise Exception("You cannot access body after reading from request's data stream")
|
2012-02-11 06:51:07 +08:00
|
|
|
try:
|
|
|
|
self._body = self.read()
|
2012-04-29 00:09:37 +08:00
|
|
|
except IOError as e:
|
2012-02-11 06:51:07 +08:00
|
|
|
raise UnreadablePostError, e, sys.exc_traceback
|
2012-05-06 01:47:03 +08:00
|
|
|
self._stream = BytesIO(self._body)
|
2011-12-17 07:40:32 +08:00
|
|
|
return self._body
|
|
|
|
|
|
|
|
@property
|
|
|
|
def raw_post_data(self):
|
2012-05-03 21:27:01 +08:00
|
|
|
warnings.warn('HttpRequest.raw_post_data has been deprecated. Use HttpRequest.body instead.', DeprecationWarning)
|
2011-12-17 07:40:32 +08:00
|
|
|
return self.body
|
2010-10-30 00:39:25 +08:00
|
|
|
|
|
|
|
def _mark_post_parse_error(self):
|
|
|
|
self._post = QueryDict('')
|
|
|
|
self._files = MultiValueDict()
|
|
|
|
self._post_parse_error = True
|
|
|
|
|
|
|
|
def _load_post_and_files(self):
|
|
|
|
# Populates self._post and self._files
|
|
|
|
if self.method != 'POST':
|
|
|
|
self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()
|
|
|
|
return
|
2011-12-17 07:40:32 +08:00
|
|
|
if self._read_started and not hasattr(self, '_body'):
|
2010-10-30 00:39:25 +08:00
|
|
|
self._mark_post_parse_error()
|
|
|
|
return
|
|
|
|
|
|
|
|
if self.META.get('CONTENT_TYPE', '').startswith('multipart'):
|
2011-12-17 07:40:32 +08:00
|
|
|
if hasattr(self, '_body'):
|
2011-03-29 00:11:40 +08:00
|
|
|
# Use already read data
|
2012-05-06 01:47:03 +08:00
|
|
|
data = BytesIO(self._body)
|
2011-03-29 00:11:40 +08:00
|
|
|
else:
|
|
|
|
data = self
|
2010-10-30 00:39:25 +08:00
|
|
|
try:
|
2011-03-29 00:11:40 +08:00
|
|
|
self._post, self._files = self.parse_file_upload(self.META, data)
|
2010-10-30 00:39:25 +08:00
|
|
|
except:
|
2011-12-17 10:40:35 +08:00
|
|
|
# An error occured while parsing POST data. Since when
|
2010-10-30 00:39:25 +08:00
|
|
|
# formatting the error the request handler might access
|
|
|
|
# self.POST, set self._post and self._file to prevent
|
|
|
|
# attempts to parse POST data again.
|
2011-12-17 10:40:35 +08:00
|
|
|
# Mark that an error occured. This allows self.__repr__ to
|
2010-10-30 00:39:25 +08:00
|
|
|
# be explicit about it instead of simply representing an
|
|
|
|
# empty POST
|
|
|
|
self._mark_post_parse_error()
|
|
|
|
raise
|
|
|
|
else:
|
2011-12-17 07:40:32 +08:00
|
|
|
self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
|
2010-10-30 00:39:25 +08:00
|
|
|
|
|
|
|
## File-like and iterator interface.
|
|
|
|
##
|
|
|
|
## Expects self._stream to be set to an appropriate source of bytes by
|
2012-03-31 18:34:11 +08:00
|
|
|
## a corresponding request subclass (e.g. WSGIRequest).
|
2010-10-30 00:39:25 +08:00
|
|
|
## Also when request data has already been read by request.POST or
|
2012-05-06 01:47:03 +08:00
|
|
|
## request.body, self._stream points to a BytesIO instance
|
2010-10-30 00:39:25 +08:00
|
|
|
## containing that data.
|
|
|
|
|
|
|
|
def read(self, *args, **kwargs):
|
|
|
|
self._read_started = True
|
|
|
|
return self._stream.read(*args, **kwargs)
|
|
|
|
|
|
|
|
def readline(self, *args, **kwargs):
|
|
|
|
self._read_started = True
|
|
|
|
return self._stream.readline(*args, **kwargs)
|
|
|
|
|
|
|
|
def xreadlines(self):
|
|
|
|
while True:
|
|
|
|
buf = self.readline()
|
|
|
|
if not buf:
|
|
|
|
break
|
|
|
|
yield buf
|
|
|
|
__iter__ = xreadlines
|
|
|
|
|
|
|
|
def readlines(self):
|
|
|
|
return list(iter(self))
|
|
|
|
|
2005-11-30 10:35:06 +08:00
|
|
|
class QueryDict(MultiValueDict):
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
"""
|
|
|
|
A specialized MultiValueDict that takes a query string when initialized.
|
|
|
|
This is immutable unless you create a copy of it.
|
|
|
|
|
|
|
|
Values retrieved from this class are converted from the given encoding
|
|
|
|
(DEFAULT_CHARSET by default) to unicode.
|
|
|
|
"""
|
2008-08-21 21:55:21 +08:00
|
|
|
# These are both reset in __init__, but is specified here at the class
|
|
|
|
# level so that unpickling will have valid values
|
|
|
|
_mutable = True
|
|
|
|
_encoding = None
|
|
|
|
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
def __init__(self, query_string, mutable=False, encoding=None):
|
2005-11-30 12:08:46 +08:00
|
|
|
MultiValueDict.__init__(self)
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
if not encoding:
|
2007-07-11 14:55:12 +08:00
|
|
|
encoding = settings.DEFAULT_CHARSET
|
|
|
|
self.encoding = encoding
|
2005-11-30 12:13:21 +08:00
|
|
|
for key, value in parse_qsl((query_string or ''), True): # keep_blank_values=True
|
2008-03-08 11:46:33 +08:00
|
|
|
self.appendlist(force_unicode(key, encoding, errors='replace'),
|
|
|
|
force_unicode(value, encoding, errors='replace'))
|
2006-03-29 01:31:04 +08:00
|
|
|
self._mutable = mutable
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2008-08-21 21:55:21 +08:00
|
|
|
def _get_encoding(self):
|
|
|
|
if self._encoding is None:
|
|
|
|
self._encoding = settings.DEFAULT_CHARSET
|
|
|
|
return self._encoding
|
|
|
|
|
|
|
|
def _set_encoding(self, value):
|
|
|
|
self._encoding = value
|
|
|
|
|
|
|
|
encoding = property(_get_encoding, _set_encoding)
|
|
|
|
|
2005-11-30 12:08:46 +08:00
|
|
|
def _assert_mutable(self):
|
2005-07-13 09:25:57 +08:00
|
|
|
if not self._mutable:
|
2008-03-08 11:46:33 +08:00
|
|
|
raise AttributeError("This QueryDict instance is immutable")
|
2005-11-30 12:08:46 +08:00
|
|
|
|
2006-03-29 01:31:04 +08:00
|
|
|
def __setitem__(self, key, value):
|
2005-11-30 12:08:46 +08:00
|
|
|
self._assert_mutable()
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
key = str_to_unicode(key, self.encoding)
|
|
|
|
value = str_to_unicode(value, self.encoding)
|
2005-11-30 12:08:46 +08:00
|
|
|
MultiValueDict.__setitem__(self, key, value)
|
2006-03-29 01:31:04 +08:00
|
|
|
|
2007-05-11 16:22:06 +08:00
|
|
|
def __delitem__(self, key):
|
|
|
|
self._assert_mutable()
|
|
|
|
super(QueryDict, self).__delitem__(key)
|
|
|
|
|
2006-03-29 01:31:04 +08:00
|
|
|
def __copy__(self):
|
2010-05-29 00:39:52 +08:00
|
|
|
result = self.__class__('', mutable=True, encoding=self.encoding)
|
2006-03-29 01:31:04 +08:00
|
|
|
for key, value in dict.items(self):
|
|
|
|
dict.__setitem__(result, key, value)
|
|
|
|
return result
|
|
|
|
|
2008-02-27 15:58:00 +08:00
|
|
|
def __deepcopy__(self, memo):
|
2011-03-28 10:11:19 +08:00
|
|
|
import copy
|
2010-05-29 00:39:52 +08:00
|
|
|
result = self.__class__('', mutable=True, encoding=self.encoding)
|
2006-03-29 01:31:04 +08:00
|
|
|
memo[id(self)] = result
|
|
|
|
for key, value in dict.items(self):
|
|
|
|
dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo))
|
|
|
|
return result
|
2010-10-30 00:39:25 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def setlist(self, key, list_):
|
2005-11-30 12:08:46 +08:00
|
|
|
self._assert_mutable()
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
key = str_to_unicode(key, self.encoding)
|
|
|
|
list_ = [str_to_unicode(elt, self.encoding) for elt in list_]
|
2005-11-30 12:08:46 +08:00
|
|
|
MultiValueDict.setlist(self, key, list_)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
def setlistdefault(self, key, default_list=()):
|
|
|
|
self._assert_mutable()
|
|
|
|
if key not in self:
|
|
|
|
self.setlist(key, default_list)
|
|
|
|
return MultiValueDict.getlist(self, key)
|
|
|
|
|
2005-11-30 12:08:46 +08:00
|
|
|
def appendlist(self, key, value):
|
|
|
|
self._assert_mutable()
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
key = str_to_unicode(key, self.encoding)
|
|
|
|
value = str_to_unicode(value, self.encoding)
|
2005-11-30 12:08:46 +08:00
|
|
|
MultiValueDict.appendlist(self, key, value)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-11-30 12:08:46 +08:00
|
|
|
def update(self, other_dict):
|
|
|
|
self._assert_mutable()
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
f = lambda s: str_to_unicode(s, self.encoding)
|
2008-08-30 00:49:19 +08:00
|
|
|
if hasattr(other_dict, 'lists'):
|
|
|
|
for key, valuelist in other_dict.lists():
|
|
|
|
for value in valuelist:
|
|
|
|
MultiValueDict.update(self, {f(key): f(value)})
|
|
|
|
else:
|
|
|
|
d = dict([(f(k), f(v)) for k, v in other_dict.items()])
|
|
|
|
MultiValueDict.update(self, d)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2007-05-20 02:34:00 +08:00
|
|
|
def pop(self, key, *args):
|
2005-11-30 12:08:46 +08:00
|
|
|
self._assert_mutable()
|
2007-05-20 02:34:00 +08:00
|
|
|
return MultiValueDict.pop(self, key, *args)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-11-30 12:08:46 +08:00
|
|
|
def popitem(self):
|
|
|
|
self._assert_mutable()
|
|
|
|
return MultiValueDict.popitem(self)
|
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
self._assert_mutable()
|
|
|
|
MultiValueDict.clear(self)
|
|
|
|
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
def setdefault(self, key, default=None):
|
2005-11-30 12:08:46 +08:00
|
|
|
self._assert_mutable()
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
key = str_to_unicode(key, self.encoding)
|
|
|
|
default = str_to_unicode(default, self.encoding)
|
|
|
|
return MultiValueDict.setdefault(self, key, default)
|
2005-11-30 12:08:46 +08:00
|
|
|
|
|
|
|
def copy(self):
|
2008-03-08 11:46:33 +08:00
|
|
|
"""Returns a mutable copy of this object."""
|
2008-02-27 15:58:00 +08:00
|
|
|
return self.__deepcopy__({})
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2010-12-02 06:25:17 +08:00
|
|
|
def urlencode(self, safe=None):
|
|
|
|
"""
|
|
|
|
Returns an encoded string of all query string arguments.
|
|
|
|
|
|
|
|
:arg safe: Used to specify characters which do not require quoting, for
|
|
|
|
example::
|
|
|
|
|
|
|
|
>>> q = QueryDict('', mutable=True)
|
|
|
|
>>> q['next'] = '/a&b/'
|
|
|
|
>>> q.urlencode()
|
|
|
|
'next=%2Fa%26b%2F'
|
|
|
|
>>> q.urlencode(safe='/')
|
|
|
|
'next=/a%26b/'
|
|
|
|
|
|
|
|
"""
|
2005-09-03 03:39:47 +08:00
|
|
|
output = []
|
2010-12-02 06:25:17 +08:00
|
|
|
if safe:
|
2012-06-08 00:08:47 +08:00
|
|
|
safe = smart_str(safe, self.encoding)
|
2010-12-02 06:25:17 +08:00
|
|
|
encode = lambda k, v: '%s=%s' % ((quote(k, safe), quote(v, safe)))
|
|
|
|
else:
|
|
|
|
encode = lambda k, v: urlencode({k: v})
|
2005-11-30 12:08:46 +08:00
|
|
|
for k, list_ in self.lists():
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
k = smart_str(k, self.encoding)
|
2010-12-02 06:25:17 +08:00
|
|
|
output.extend([encode(k, smart_str(v, self.encoding))
|
|
|
|
for v in list_])
|
2005-09-03 03:39:47 +08:00
|
|
|
return '&'.join(output)
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def parse_cookie(cookie):
|
|
|
|
if cookie == '':
|
|
|
|
return {}
|
2010-11-26 21:30:50 +08:00
|
|
|
if not isinstance(cookie, Cookie.BaseCookie):
|
2009-12-12 23:30:25 +08:00
|
|
|
try:
|
2011-01-25 04:35:46 +08:00
|
|
|
c = SimpleCookie()
|
2011-06-29 23:12:48 +08:00
|
|
|
c.load(cookie)
|
2010-11-26 21:30:50 +08:00
|
|
|
except Cookie.CookieError:
|
2009-12-12 23:30:25 +08:00
|
|
|
# Invalid cookie
|
|
|
|
return {}
|
|
|
|
else:
|
|
|
|
c = cookie
|
2005-07-13 09:25:57 +08:00
|
|
|
cookiedict = {}
|
|
|
|
for key in c.keys():
|
|
|
|
cookiedict[key] = c.get(key).value
|
|
|
|
return cookiedict
|
|
|
|
|
2009-05-08 19:15:23 +08:00
|
|
|
class BadHeaderError(ValueError):
|
|
|
|
pass
|
|
|
|
|
2006-04-10 07:54:34 +08:00
|
|
|
class HttpResponse(object):
|
2008-03-08 11:46:33 +08:00
|
|
|
"""A basic HTTP response, with content and dictionary-accessed headers."""
|
2007-03-30 14:46:36 +08:00
|
|
|
|
|
|
|
status_code = 200
|
|
|
|
|
2007-08-11 17:37:42 +08:00
|
|
|
def __init__(self, content='', mimetype=None, status=None,
|
|
|
|
content_type=None):
|
2010-09-11 09:41:53 +08:00
|
|
|
# _headers is a mapping of the lower-case name to the original case of
|
|
|
|
# the header (required for working with legacy systems) and the header
|
2011-12-17 10:40:35 +08:00
|
|
|
# value. Both the name of the header and its value are ASCII strings.
|
2010-09-11 09:41:53 +08:00
|
|
|
self._headers = {}
|
2006-04-10 08:01:59 +08:00
|
|
|
self._charset = settings.DEFAULT_CHARSET
|
2011-12-17 10:40:35 +08:00
|
|
|
if mimetype: # For backwards compatibility.
|
|
|
|
content_type = mimetype
|
2007-08-11 17:37:42 +08:00
|
|
|
if not content_type:
|
|
|
|
content_type = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE,
|
2010-09-11 09:41:53 +08:00
|
|
|
self._charset)
|
2011-09-15 07:58:12 +08:00
|
|
|
self.content = content
|
2011-01-25 04:35:46 +08:00
|
|
|
self.cookies = SimpleCookie()
|
2007-06-27 21:02:38 +08:00
|
|
|
if status:
|
|
|
|
self.status_code = status
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2010-09-11 09:41:53 +08:00
|
|
|
self['Content-Type'] = content_type
|
2007-10-20 13:58:48 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def __str__(self):
|
2008-03-08 11:46:33 +08:00
|
|
|
"""Full HTTP message, including headers."""
|
2005-07-13 09:25:57 +08:00
|
|
|
return '\n'.join(['%s: %s' % (key, value)
|
2007-10-20 13:58:48 +08:00
|
|
|
for key, value in self._headers.values()]) \
|
2005-07-13 09:25:57 +08:00
|
|
|
+ '\n\n' + self.content
|
|
|
|
|
2007-12-17 16:05:51 +08:00
|
|
|
def _convert_to_ascii(self, *values):
|
2008-03-08 11:46:33 +08:00
|
|
|
"""Converts all values to ascii strings."""
|
2007-12-17 16:05:51 +08:00
|
|
|
for value in values:
|
|
|
|
if isinstance(value, unicode):
|
|
|
|
try:
|
2009-05-08 19:31:36 +08:00
|
|
|
value = value.encode('us-ascii')
|
2012-04-29 00:09:37 +08:00
|
|
|
except UnicodeError as e:
|
2007-12-17 16:05:51 +08:00
|
|
|
e.reason += ', HTTP response headers must be in US-ASCII format'
|
|
|
|
raise
|
|
|
|
else:
|
2009-05-08 19:31:36 +08:00
|
|
|
value = str(value)
|
|
|
|
if '\n' in value or '\r' in value:
|
|
|
|
raise BadHeaderError("Header values can't contain newlines (got %r)" % (value))
|
|
|
|
yield value
|
2007-12-17 16:05:51 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def __setitem__(self, header, value):
|
2007-12-17 16:05:51 +08:00
|
|
|
header, value = self._convert_to_ascii(header, value)
|
2007-10-20 13:58:48 +08:00
|
|
|
self._headers[header.lower()] = (header, value)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def __delitem__(self, header):
|
|
|
|
try:
|
2007-09-15 05:53:13 +08:00
|
|
|
del self._headers[header.lower()]
|
2005-07-13 09:25:57 +08:00
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def __getitem__(self, header):
|
2007-10-20 13:58:48 +08:00
|
|
|
return self._headers[header.lower()][1]
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2011-12-12 05:04:56 +08:00
|
|
|
def __getstate__(self):
|
|
|
|
# SimpleCookie is not pickeable with pickle.HIGHEST_PROTOCOL, so we
|
|
|
|
# serialise to a string instead
|
|
|
|
state = self.__dict__.copy()
|
|
|
|
state['cookies'] = str(state['cookies'])
|
|
|
|
return state
|
|
|
|
|
|
|
|
def __setstate__(self, state):
|
|
|
|
self.__dict__.update(state)
|
|
|
|
self.cookies = SimpleCookie(self.cookies)
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def has_header(self, header):
|
2008-03-08 11:46:33 +08:00
|
|
|
"""Case-insensitive check for a header."""
|
2011-09-10 03:33:40 +08:00
|
|
|
return header.lower() in self._headers
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2007-09-15 05:41:48 +08:00
|
|
|
__contains__ = has_header
|
2007-10-20 11:32:21 +08:00
|
|
|
|
2007-09-15 06:33:56 +08:00
|
|
|
def items(self):
|
2007-10-20 13:58:48 +08:00
|
|
|
return self._headers.values()
|
2007-10-20 11:32:21 +08:00
|
|
|
|
2011-06-17 00:34:46 +08:00
|
|
|
def get(self, header, alternate=None):
|
2007-10-20 13:58:48 +08:00
|
|
|
return self._headers.get(header.lower(), (None, alternate))[1]
|
2007-09-15 05:41:48 +08:00
|
|
|
|
2008-03-08 11:46:33 +08:00
|
|
|
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
|
2010-11-26 21:30:50 +08:00
|
|
|
domain=None, secure=False, httponly=False):
|
2010-09-13 04:52:49 +08:00
|
|
|
"""
|
|
|
|
Sets a cookie.
|
|
|
|
|
2012-03-19 04:58:22 +08:00
|
|
|
``expires`` can be:
|
|
|
|
- a string in the correct format,
|
|
|
|
- a naive ``datetime.datetime`` object in UTC,
|
|
|
|
- an aware ``datetime.datetime`` object in any time zone.
|
|
|
|
If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
|
|
|
|
|
2010-09-13 04:52:49 +08:00
|
|
|
"""
|
2005-07-13 09:25:57 +08:00
|
|
|
self.cookies[key] = value
|
2010-09-13 04:52:49 +08:00
|
|
|
if expires is not None:
|
|
|
|
if isinstance(expires, datetime.datetime):
|
2012-03-19 04:58:22 +08:00
|
|
|
if timezone.is_aware(expires):
|
|
|
|
expires = timezone.make_naive(expires, timezone.utc)
|
2010-09-13 04:52:49 +08:00
|
|
|
delta = expires - expires.utcnow()
|
|
|
|
# Add one second so the date matches exactly (a fraction of
|
|
|
|
# time gets lost between converting to a timedelta and
|
|
|
|
# then the date string).
|
|
|
|
delta = delta + datetime.timedelta(seconds=1)
|
|
|
|
# Just set max_age - the max_age logic will set expires.
|
|
|
|
expires = None
|
|
|
|
max_age = max(0, delta.days * 86400 + delta.seconds)
|
|
|
|
else:
|
|
|
|
self.cookies[key]['expires'] = expires
|
2008-03-08 11:31:42 +08:00
|
|
|
if max_age is not None:
|
|
|
|
self.cookies[key]['max-age'] = max_age
|
2010-09-13 04:52:49 +08:00
|
|
|
# IE requires expires, so set it if hasn't been already.
|
|
|
|
if not expires:
|
|
|
|
self.cookies[key]['expires'] = cookie_date(time.time() +
|
2010-10-30 00:39:25 +08:00
|
|
|
max_age)
|
2008-03-08 11:31:42 +08:00
|
|
|
if path is not None:
|
|
|
|
self.cookies[key]['path'] = path
|
|
|
|
if domain is not None:
|
|
|
|
self.cookies[key]['domain'] = domain
|
|
|
|
if secure:
|
|
|
|
self.cookies[key]['secure'] = True
|
2010-11-26 21:30:50 +08:00
|
|
|
if httponly:
|
|
|
|
self.cookies[key]['httponly'] = True
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
def set_signed_cookie(self, key, value, salt='', **kwargs):
|
|
|
|
value = signing.get_cookie_signer(salt=key + salt).sign(value)
|
|
|
|
return self.set_cookie(key, value, **kwargs)
|
|
|
|
|
2006-08-09 23:40:24 +08:00
|
|
|
def delete_cookie(self, key, path='/', domain=None):
|
2007-10-20 15:01:12 +08:00
|
|
|
self.set_cookie(key, max_age=0, path=path, domain=domain,
|
2008-03-08 11:46:33 +08:00
|
|
|
expires='Thu, 01-Jan-1970 00:00:00 GMT')
|
2005-09-23 09:17:39 +08:00
|
|
|
|
2006-04-10 07:54:34 +08:00
|
|
|
def _get_content(self):
|
2007-10-20 14:50:16 +08:00
|
|
|
if self.has_header('Content-Encoding'):
|
2012-05-19 23:43:34 +08:00
|
|
|
return b''.join([str(e) for e in self._container])
|
|
|
|
return b''.join([smart_str(e, self._charset) for e in self._container])
|
2006-04-10 07:54:34 +08:00
|
|
|
|
|
|
|
def _set_content(self, value):
|
2011-09-15 07:27:35 +08:00
|
|
|
if hasattr(value, '__iter__'):
|
|
|
|
self._container = value
|
|
|
|
self._base_content_is_iter = True
|
|
|
|
else:
|
|
|
|
self._container = [value]
|
|
|
|
self._base_content_is_iter = False
|
2006-04-10 07:54:34 +08:00
|
|
|
|
|
|
|
content = property(_get_content, _set_content)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-09-22 20:32:00 +08:00
|
|
|
def __iter__(self):
|
2007-09-15 03:55:24 +08:00
|
|
|
self._iterator = iter(self._container)
|
2007-06-22 15:15:04 +08:00
|
|
|
return self
|
|
|
|
|
|
|
|
def next(self):
|
2012-05-11 02:14:04 +08:00
|
|
|
chunk = next(self._iterator)
|
2007-06-22 15:15:04 +08:00
|
|
|
if isinstance(chunk, unicode):
|
|
|
|
chunk = chunk.encode(self._charset)
|
2007-12-05 17:28:56 +08:00
|
|
|
return str(chunk)
|
2006-09-22 20:32:00 +08:00
|
|
|
|
|
|
|
def close(self):
|
|
|
|
if hasattr(self._container, 'close'):
|
|
|
|
self._container.close()
|
2006-04-11 21:43:29 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
# The remaining methods partially implement the file-like object interface.
|
|
|
|
# See http://docs.python.org/lib/bltin-file-objects.html
|
|
|
|
def write(self, content):
|
2011-09-15 07:27:35 +08:00
|
|
|
if self._base_content_is_iter:
|
2008-03-08 11:46:33 +08:00
|
|
|
raise Exception("This %s instance is not writable" % self.__class__)
|
2006-09-22 20:32:00 +08:00
|
|
|
self._container.append(content)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def flush(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def tell(self):
|
2011-09-15 07:27:35 +08:00
|
|
|
if self._base_content_is_iter:
|
2008-03-08 11:46:33 +08:00
|
|
|
raise Exception("This %s instance cannot tell its position" % self.__class__)
|
2011-09-15 07:27:35 +08:00
|
|
|
return sum([len(str(chunk)) for chunk in self._container])
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
class HttpResponseRedirect(HttpResponse):
|
2007-03-30 14:46:36 +08:00
|
|
|
status_code = 302
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def __init__(self, redirect_to):
|
2011-03-09 12:09:47 +08:00
|
|
|
super(HttpResponseRedirect, self).__init__()
|
2010-03-03 03:37:48 +08:00
|
|
|
self['Location'] = iri_to_uri(redirect_to)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-01-04 07:57:14 +08:00
|
|
|
class HttpResponsePermanentRedirect(HttpResponse):
|
2007-03-30 14:46:36 +08:00
|
|
|
status_code = 301
|
|
|
|
|
2006-01-04 07:57:14 +08:00
|
|
|
def __init__(self, redirect_to):
|
2011-03-09 12:09:47 +08:00
|
|
|
super(HttpResponsePermanentRedirect, self).__init__()
|
2010-03-03 03:37:48 +08:00
|
|
|
self['Location'] = iri_to_uri(redirect_to)
|
2006-01-04 07:57:14 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
class HttpResponseNotModified(HttpResponse):
|
2007-03-30 14:46:36 +08:00
|
|
|
status_code = 304
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2007-03-30 14:48:19 +08:00
|
|
|
class HttpResponseBadRequest(HttpResponse):
|
|
|
|
status_code = 400
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
class HttpResponseNotFound(HttpResponse):
|
2007-03-30 14:46:36 +08:00
|
|
|
status_code = 404
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
class HttpResponseForbidden(HttpResponse):
|
2007-03-30 14:46:36 +08:00
|
|
|
status_code = 403
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-06-19 10:04:37 +08:00
|
|
|
class HttpResponseNotAllowed(HttpResponse):
|
2007-03-30 14:46:36 +08:00
|
|
|
status_code = 405
|
|
|
|
|
2006-06-19 10:04:37 +08:00
|
|
|
def __init__(self, permitted_methods):
|
2011-03-09 12:09:47 +08:00
|
|
|
super(HttpResponseNotAllowed, self).__init__()
|
2006-06-19 10:04:37 +08:00
|
|
|
self['Allow'] = ', '.join(permitted_methods)
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
class HttpResponseGone(HttpResponse):
|
2007-03-30 14:46:36 +08:00
|
|
|
status_code = 410
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
class HttpResponseServerError(HttpResponse):
|
2007-03-30 14:46:36 +08:00
|
|
|
status_code = 500
|
|
|
|
|
2007-09-16 01:46:03 +08:00
|
|
|
# A backwards compatible alias for HttpRequest.get_host.
|
2006-05-02 09:31:56 +08:00
|
|
|
def get_host(request):
|
2007-09-16 01:46:03 +08:00
|
|
|
return request.get_host()
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
|
|
|
# It's neither necessary nor appropriate to use
|
|
|
|
# django.utils.encoding.smart_unicode for parsing URLs and form inputs. Thus,
|
|
|
|
# this slightly more restricted function.
|
|
|
|
def str_to_unicode(s, encoding):
|
|
|
|
"""
|
2008-03-08 11:46:33 +08:00
|
|
|
Converts basestring objects to unicode, using the given encoding. Illegally
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
encoded input characters are replaced with Unicode "unknown" codepoint
|
|
|
|
(\ufffd).
|
|
|
|
|
|
|
|
Returns any non-basestring objects without change.
|
|
|
|
"""
|
|
|
|
if isinstance(s, str):
|
|
|
|
return unicode(s, encoding, 'replace')
|
|
|
|
else:
|
|
|
|
return s
|
2008-07-21 15:57:10 +08:00
|
|
|
|