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
|
2010-09-13 04:52:49 +08:00
|
|
|
import time
|
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
|
2007-09-14 13:28:00 +08:00
|
|
|
from urlparse import urljoin
|
2010-10-30 00:39:25 +08:00
|
|
|
try:
|
|
|
|
from cStringIO import StringIO
|
|
|
|
except ImportError:
|
|
|
|
from StringIO import StringIO
|
2008-03-08 11:46:33 +08:00
|
|
|
try:
|
|
|
|
# The mod_python version is more efficient, so try importing it first.
|
|
|
|
from mod_python.util import parse_qsl
|
|
|
|
except ImportError:
|
2010-10-20 21:07:06 +08:00
|
|
|
try:
|
|
|
|
# Python 2.6 and greater
|
|
|
|
from urlparse import parse_qsl
|
|
|
|
except ImportError:
|
2011-06-10 04:01:28 +08:00
|
|
|
# Python 2.5. Works on Python 2.6 but raises PendingDeprecationWarning
|
2010-10-20 21:07:06 +08:00
|
|
|
from cgi import parse_qsl
|
2008-03-08 11:46:33 +08:00
|
|
|
|
2011-01-25 04:35:46 +08:00
|
|
|
import Cookie
|
2010-11-26 21:30:50 +08:00
|
|
|
# httponly support exists in Python 2.6's Cookie library,
|
2011-06-10 04:01:28 +08:00
|
|
|
# but not in Python 2.5.
|
2011-01-25 04:35:46 +08:00
|
|
|
_morsel_supports_httponly = Cookie.Morsel._reserved.has_key('httponly')
|
|
|
|
# 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:
|
|
|
|
_tc.load('foo:bar=1')
|
|
|
|
_cookie_allows_colon_in_names = True
|
|
|
|
except Cookie.CookieError:
|
|
|
|
_cookie_allows_colon_in_names = False
|
2011-01-25 04:35:46 +08:00
|
|
|
|
2011-02-13 10:24:05 +08:00
|
|
|
if _morsel_supports_httponly and _cookie_encodes_correctly and _cookie_allows_colon_in_names:
|
2010-11-26 21:30:50 +08:00
|
|
|
SimpleCookie = Cookie.SimpleCookie
|
|
|
|
else:
|
2011-01-25 04:35:46 +08:00
|
|
|
if not _morsel_supports_httponly:
|
|
|
|
class Morsel(Cookie.Morsel):
|
|
|
|
def __setitem__(self, K, V):
|
|
|
|
K = K.lower()
|
|
|
|
if K == "httponly":
|
|
|
|
if V:
|
|
|
|
# The superclass rejects httponly as a key,
|
|
|
|
# so we jump to the grandparent.
|
|
|
|
super(Cookie.Morsel, self).__setitem__(K, V)
|
|
|
|
else:
|
|
|
|
super(Morsel, self).__setitem__(K, V)
|
|
|
|
|
|
|
|
def OutputString(self, attrs=None):
|
|
|
|
output = super(Morsel, self).OutputString(attrs)
|
|
|
|
if "httponly" in self:
|
|
|
|
output += "; httponly"
|
|
|
|
return output
|
2011-07-08 20:07:54 +08:00
|
|
|
else:
|
|
|
|
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.
|
|
|
|
# and non-ASCII chars. We just make use of this mechanism, to
|
|
|
|
# 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
|
|
|
|
2011-07-08 20:07:54 +08:00
|
|
|
if not _cookie_allows_colon_in_names or not _morsel_supports_httponly:
|
2011-06-29 23:12:48 +08:00
|
|
|
def load(self, rawdata):
|
|
|
|
self.bad_cookies = set()
|
2011-02-13 10:24:05 +08:00
|
|
|
super(SimpleCookie, self).load(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):
|
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
|
|
|
|
|
|
|
|
2011-01-25 04:35:46 +08:00
|
|
|
class CompatCookie(SimpleCookie):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(CompatCookie, self).__init__(*args, **kwargs)
|
|
|
|
import warnings
|
|
|
|
warnings.warn("CompatCookie is deprecated, use django.http.SimpleCookie instead.",
|
2011-04-02 16:40:38 +08:00
|
|
|
DeprecationWarning)
|
2010-11-26 21:30:50 +08:00
|
|
|
|
2008-07-01 23:10:51 +08:00
|
|
|
from django.utils.datastructures import MultiValueDict, ImmutableList
|
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
|
|
|
from django.utils.encoding import smart_str, iri_to_uri, force_unicode
|
2010-09-13 04:52:49 +08:00
|
|
|
from django.utils.http import cookie_date
|
2008-07-01 23:10:51 +08:00
|
|
|
from django.http.multipartparser import MultiPartParser
|
|
|
|
from django.conf import settings
|
2011-05-21 22:41:14 +08:00
|
|
|
from django.core import signing
|
2008-07-01 23:10:51 +08:00
|
|
|
from django.core.files import uploadhandler
|
2007-11-11 11:55:44 +08:00
|
|
|
from utils import *
|
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
|
|
|
|
return smart_str(u'<%s\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' %
|
|
|
|
(request.__class__.__name__,
|
|
|
|
path,
|
|
|
|
unicode(get),
|
|
|
|
unicode(post),
|
|
|
|
unicode(cookies),
|
|
|
|
unicode(meta)))
|
|
|
|
|
|
|
|
|
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.
|
2007-10-04 06:21:43 +08:00
|
|
|
if 'HTTP_X_FORWARDED_HOST' in self.META:
|
|
|
|
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
|
|
|
|
2006-07-22 00:20:22 +08:00
|
|
|
def is_secure(self):
|
|
|
|
return os.environ.get("HTTPS") == "on"
|
2005-07-13 09:25:57 +08:00
|
|
|
|
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
|
|
|
|
2010-10-30 00:39:25 +08:00
|
|
|
def _get_raw_post_data(self):
|
|
|
|
if not hasattr(self, '_raw_post_data'):
|
|
|
|
if self._read_started:
|
|
|
|
raise Exception("You cannot access raw_post_data after reading from request's data stream")
|
2011-06-28 18:17:56 +08:00
|
|
|
self._raw_post_data = self.read()
|
2010-10-30 00:39:25 +08:00
|
|
|
self._stream = StringIO(self._raw_post_data)
|
|
|
|
return self._raw_post_data
|
|
|
|
raw_post_data = property(_get_raw_post_data)
|
|
|
|
|
|
|
|
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-03-29 00:11:40 +08:00
|
|
|
if self._read_started and not hasattr(self, '_raw_post_data'):
|
2010-10-30 00:39:25 +08:00
|
|
|
self._mark_post_parse_error()
|
|
|
|
return
|
|
|
|
|
|
|
|
if self.META.get('CONTENT_TYPE', '').startswith('multipart'):
|
2011-03-29 00:11:40 +08:00
|
|
|
if hasattr(self, '_raw_post_data'):
|
|
|
|
# Use already read data
|
|
|
|
data = StringIO(self._raw_post_data)
|
|
|
|
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:
|
|
|
|
# An error occured while parsing POST data. Since when
|
|
|
|
# formatting the error the request handler might access
|
|
|
|
# self.POST, set self._post and self._file to prevent
|
|
|
|
# attempts to parse POST data again.
|
|
|
|
# Mark that an error occured. This allows self.__repr__ to
|
|
|
|
# be explicit about it instead of simply representing an
|
|
|
|
# empty POST
|
|
|
|
self._mark_post_parse_error()
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
self._post, self._files = QueryDict(self.raw_post_data, encoding=self._encoding), MultiValueDict()
|
|
|
|
|
|
|
|
## File-like and iterator interface.
|
|
|
|
##
|
|
|
|
## Expects self._stream to be set to an appropriate source of bytes by
|
|
|
|
## a corresponding request subclass (WSGIRequest or ModPythonRequest).
|
|
|
|
## Also when request data has already been read by request.POST or
|
|
|
|
## request.raw_post_data, self._stream points to a StringIO instance
|
|
|
|
## 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:
|
|
|
|
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
|
|
|
|
# value. Both the name of the header and its value are ASCII strings.
|
|
|
|
self._headers = {}
|
2006-04-10 08:01:59 +08:00
|
|
|
self._charset = settings.DEFAULT_CHARSET
|
2007-08-11 17:37:42 +08:00
|
|
|
if mimetype:
|
|
|
|
content_type = mimetype # For backwards compatibility
|
|
|
|
if not content_type:
|
|
|
|
content_type = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE,
|
2010-09-11 09:41:53 +08:00
|
|
|
self._charset)
|
2007-02-10 11:56:21 +08:00
|
|
|
if not isinstance(content, basestring) and hasattr(content, '__iter__'):
|
2006-09-22 20:32:00 +08:00
|
|
|
self._container = content
|
2006-04-10 07:54:34 +08:00
|
|
|
self._is_string = False
|
|
|
|
else:
|
2006-09-22 20:32:00 +08:00
|
|
|
self._container = [content]
|
2006-04-10 07:54:34 +08:00
|
|
|
self._is_string = True
|
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')
|
2007-12-17 16:05:51 +08:00
|
|
|
except UnicodeError, e:
|
|
|
|
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
|
|
|
|
|
|
|
def has_header(self, header):
|
2008-03-08 11:46:33 +08:00
|
|
|
"""Case-insensitive check for a header."""
|
2007-09-15 05:53:13 +08:00
|
|
|
return self._headers.has_key(header.lower())
|
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.
|
|
|
|
|
2010-10-30 00:39:25 +08:00
|
|
|
``expires`` can be a string in the correct format or a
|
2010-09-13 04:52:49 +08:00
|
|
|
``datetime.datetime`` object in UTC. If ``expires`` is a datetime
|
|
|
|
object then ``max_age`` will be calculated.
|
|
|
|
"""
|
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):
|
|
|
|
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'):
|
|
|
|
return ''.join(self._container)
|
|
|
|
return smart_str(''.join(self._container), self._charset)
|
2006-04-10 07:54:34 +08:00
|
|
|
|
|
|
|
def _set_content(self, value):
|
2006-09-22 20:32:00 +08:00
|
|
|
self._container = [value]
|
2006-04-10 07:54:34 +08:00
|
|
|
self._is_string = True
|
|
|
|
|
|
|
|
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):
|
|
|
|
chunk = self._iterator.next()
|
|
|
|
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):
|
2006-04-10 07:54:34 +08:00
|
|
|
if not self._is_string:
|
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):
|
2006-04-10 07:54:34 +08:00
|
|
|
if not self._is_string:
|
2008-03-08 11:46:33 +08:00
|
|
|
raise Exception("This %s instance cannot tell its position" % self.__class__)
|
2006-09-22 20:32:00 +08:00
|
|
|
return sum([len(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
|
|
|
|