2006-07-22 00:20:22 +08:00
|
|
|
import os
|
2005-07-13 09:25:57 +08:00
|
|
|
from Cookie import SimpleCookie
|
|
|
|
from pprint import pformat
|
2006-06-20 12:06:16 +08:00
|
|
|
from urllib import urlencode, quote
|
2005-11-30 10:35:06 +08:00
|
|
|
from django.utils.datastructures import MultiValueDict
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-06-20 12:06:16 +08:00
|
|
|
RESERVED_CHARS="!*'();:@&=+$,/?%#[]"
|
|
|
|
|
2005-11-30 10:36:26 +08:00
|
|
|
try:
|
|
|
|
# The mod_python version is more efficient, so try importing it first.
|
|
|
|
from mod_python.util import parse_qsl
|
|
|
|
except ImportError:
|
|
|
|
from cgi import parse_qsl
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Http404(Exception):
|
|
|
|
pass
|
|
|
|
|
2006-06-20 11:48:31 +08:00
|
|
|
class HttpRequest(object):
|
2005-07-13 09:25:57 +08:00
|
|
|
"A basic HTTP request"
|
|
|
|
def __init__(self):
|
|
|
|
self.GET, self.POST, self.COOKIES, self.META, self.FILES = {}, {}, {}, {}, {}
|
|
|
|
self.path = ''
|
2006-06-20 11:48:31 +08:00
|
|
|
self.method = None
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '<HttpRequest\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % \
|
|
|
|
(pformat(self.GET), pformat(self.POST), pformat(self.COOKIES),
|
|
|
|
pformat(self.META))
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
for d in (self.POST, self.GET):
|
|
|
|
if d.has_key(key):
|
|
|
|
return d[key]
|
|
|
|
raise KeyError, "%s not found in either POST or GET" % key
|
|
|
|
|
2005-09-28 00:33:25 +08:00
|
|
|
def has_key(self, key):
|
|
|
|
return self.GET.has_key(key) or self.POST.has_key(key)
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def get_full_path(self):
|
|
|
|
return ''
|
2006-08-09 23:40:24 +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
|
|
|
|
2005-07-18 13:52:06 +08:00
|
|
|
def parse_file_upload(header_dict, post_data):
|
|
|
|
"Returns a tuple of (POST MultiValueDict, FILES MultiValueDict)"
|
2005-07-13 09:25:57 +08:00
|
|
|
import email, email.Message
|
|
|
|
from cgi import parse_header
|
2005-07-18 13:52:06 +08:00
|
|
|
raw_message = '\r\n'.join(['%s:%s' % pair for pair in header_dict.items()])
|
|
|
|
raw_message += '\r\n\r\n' + post_data
|
2005-07-13 09:25:57 +08:00
|
|
|
msg = email.message_from_string(raw_message)
|
2005-11-30 10:35:06 +08:00
|
|
|
POST = MultiValueDict()
|
|
|
|
FILES = MultiValueDict()
|
2005-07-13 09:25:57 +08:00
|
|
|
for submessage in msg.get_payload():
|
2007-02-27 02:52:15 +08:00
|
|
|
if submessage and isinstance(submessage, email.Message.Message):
|
2005-07-13 09:25:57 +08:00
|
|
|
name_dict = parse_header(submessage['Content-Disposition'])[1]
|
|
|
|
# name_dict is something like {'name': 'file', 'filename': 'test.txt'} for file uploads
|
|
|
|
# or {'name': 'blah'} for POST fields
|
|
|
|
# We assume all uploaded files have a 'filename' set.
|
|
|
|
if name_dict.has_key('filename'):
|
|
|
|
assert type([]) != type(submessage.get_payload()), "Nested MIME messages are not supported"
|
|
|
|
if not name_dict['filename'].strip():
|
|
|
|
continue
|
|
|
|
# IE submits the full path, so trim everything but the basename.
|
|
|
|
# (We can't use os.path.basename because it expects Linux paths.)
|
|
|
|
filename = name_dict['filename'][name_dict['filename'].rfind("\\")+1:]
|
|
|
|
FILES.appendlist(name_dict['name'], {
|
|
|
|
'filename': filename,
|
|
|
|
'content-type': (submessage.has_key('Content-Type') and submessage['Content-Type'] or None),
|
|
|
|
'content': submessage.get_payload(),
|
|
|
|
})
|
|
|
|
else:
|
|
|
|
POST.appendlist(name_dict['name'], submessage.get_payload())
|
|
|
|
return POST, FILES
|
|
|
|
|
2005-11-30 10:35:06 +08:00
|
|
|
class QueryDict(MultiValueDict):
|
2005-07-13 09:25:57 +08:00
|
|
|
"""A specialized MultiValueDict that takes a query string when initialized.
|
|
|
|
This is immutable unless you create a copy of it."""
|
2006-03-29 01:31:04 +08:00
|
|
|
def __init__(self, query_string, mutable=False):
|
2005-11-30 12:08:46 +08:00
|
|
|
MultiValueDict.__init__(self)
|
|
|
|
self._mutable = True
|
2005-11-30 12:13:21 +08:00
|
|
|
for key, value in parse_qsl((query_string or ''), True): # keep_blank_values=True
|
2005-11-30 12:08:46 +08:00
|
|
|
self.appendlist(key, value)
|
2006-03-29 01:31:04 +08:00
|
|
|
self._mutable = mutable
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-11-30 12:08:46 +08:00
|
|
|
def _assert_mutable(self):
|
2005-07-13 09:25:57 +08:00
|
|
|
if not self._mutable:
|
|
|
|
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()
|
|
|
|
MultiValueDict.__setitem__(self, key, value)
|
2006-03-29 01:31:04 +08:00
|
|
|
|
|
|
|
def __copy__(self):
|
|
|
|
result = self.__class__('', mutable=True)
|
|
|
|
for key, value in dict.items(self):
|
|
|
|
dict.__setitem__(result, key, value)
|
|
|
|
return result
|
|
|
|
|
|
|
|
def __deepcopy__(self, memo={}):
|
|
|
|
import copy
|
|
|
|
result = self.__class__('', mutable=True)
|
|
|
|
memo[id(self)] = result
|
|
|
|
for key, value in dict.items(self):
|
|
|
|
dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo))
|
|
|
|
return result
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def setlist(self, key, list_):
|
2005-11-30 12:08:46 +08:00
|
|
|
self._assert_mutable()
|
|
|
|
MultiValueDict.setlist(self, key, list_)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-11-30 12:08:46 +08:00
|
|
|
def appendlist(self, key, value):
|
|
|
|
self._assert_mutable()
|
|
|
|
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()
|
|
|
|
MultiValueDict.update(self, other_dict)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-11-30 12:08:46 +08:00
|
|
|
def pop(self, key):
|
|
|
|
self._assert_mutable()
|
|
|
|
return MultiValueDict.pop(self, key)
|
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)
|
|
|
|
|
|
|
|
def setdefault(self, *args):
|
|
|
|
self._assert_mutable()
|
|
|
|
return MultiValueDict.setdefault(self, *args)
|
|
|
|
|
|
|
|
def copy(self):
|
|
|
|
"Returns a mutable copy of this object."
|
2006-03-29 01:31:04 +08:00
|
|
|
return self.__deepcopy__()
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-09-03 03:39:47 +08:00
|
|
|
def urlencode(self):
|
|
|
|
output = []
|
2005-11-30 12:08:46 +08:00
|
|
|
for k, list_ in self.lists():
|
2005-09-03 03:39:47 +08:00
|
|
|
output.extend([urlencode({k: v}) for v in list_])
|
|
|
|
return '&'.join(output)
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def parse_cookie(cookie):
|
|
|
|
if cookie == '':
|
|
|
|
return {}
|
|
|
|
c = SimpleCookie()
|
|
|
|
c.load(cookie)
|
|
|
|
cookiedict = {}
|
|
|
|
for key in c.keys():
|
|
|
|
cookiedict[key] = c.get(key).value
|
|
|
|
return cookiedict
|
|
|
|
|
2006-04-10 07:54:34 +08:00
|
|
|
class HttpResponse(object):
|
2005-07-13 09:25:57 +08:00
|
|
|
"A basic HTTP response, with content and dictionary-accessed headers"
|
2007-03-30 14:46:36 +08:00
|
|
|
|
|
|
|
status_code = 200
|
|
|
|
|
2005-09-23 21:24:52 +08:00
|
|
|
def __init__(self, content='', mimetype=None):
|
2006-04-10 08:01:59 +08:00
|
|
|
from django.conf import settings
|
|
|
|
self._charset = settings.DEFAULT_CHARSET
|
2005-09-23 21:24:52 +08:00
|
|
|
if not mimetype:
|
2006-04-10 08:01:59 +08:00
|
|
|
mimetype = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE, settings.DEFAULT_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
|
|
|
|
self.headers = {'Content-Type': mimetype}
|
2005-07-13 09:25:57 +08:00
|
|
|
self.cookies = SimpleCookie()
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
"Full HTTP message, including headers"
|
|
|
|
return '\n'.join(['%s: %s' % (key, value)
|
|
|
|
for key, value in self.headers.items()]) \
|
|
|
|
+ '\n\n' + self.content
|
|
|
|
|
|
|
|
def __setitem__(self, header, value):
|
|
|
|
self.headers[header] = value
|
|
|
|
|
|
|
|
def __delitem__(self, header):
|
|
|
|
try:
|
|
|
|
del self.headers[header]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def __getitem__(self, header):
|
|
|
|
return self.headers[header]
|
|
|
|
|
|
|
|
def has_header(self, header):
|
|
|
|
"Case-insensitive check for a header"
|
|
|
|
header = header.lower()
|
|
|
|
for key in self.headers.keys():
|
|
|
|
if key.lower() == header:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2005-11-01 09:02:07 +08:00
|
|
|
def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=None):
|
2005-07-13 09:25:57 +08:00
|
|
|
self.cookies[key] = value
|
2005-11-01 09:02:07 +08:00
|
|
|
for var in ('max_age', 'path', 'domain', 'secure', 'expires'):
|
2005-07-13 09:25:57 +08:00
|
|
|
val = locals()[var]
|
|
|
|
if val is not None:
|
|
|
|
self.cookies[key][var.replace('_', '-')] = val
|
|
|
|
|
2006-08-09 23:40:24 +08:00
|
|
|
def delete_cookie(self, key, path='/', domain=None):
|
|
|
|
self.cookies[key] = ''
|
|
|
|
if path is not None:
|
|
|
|
self.cookies[key]['path'] = path
|
|
|
|
if domain is not None:
|
2006-11-30 00:44:10 +08:00
|
|
|
self.cookies[key]['domain'] = domain
|
2006-08-09 23:40:24 +08:00
|
|
|
self.cookies[key]['expires'] = 0
|
|
|
|
self.cookies[key]['max-age'] = 0
|
2005-09-23 09:17:39 +08:00
|
|
|
|
2006-04-10 07:54:34 +08:00
|
|
|
def _get_content(self):
|
2006-09-22 20:32:00 +08:00
|
|
|
content = ''.join(self._container)
|
2006-04-10 07:54:34 +08:00
|
|
|
if isinstance(content, unicode):
|
|
|
|
content = content.encode(self._charset)
|
|
|
|
return content
|
|
|
|
|
|
|
|
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):
|
|
|
|
self._iterator = self._container.__iter__()
|
|
|
|
return self
|
2006-04-11 21:43:29 +08:00
|
|
|
|
2006-09-22 20:32:00 +08:00
|
|
|
def next(self):
|
|
|
|
chunk = self._iterator.next()
|
|
|
|
if isinstance(chunk, unicode):
|
|
|
|
chunk = chunk.encode(self._charset)
|
|
|
|
return chunk
|
|
|
|
|
|
|
|
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:
|
|
|
|
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:
|
|
|
|
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):
|
|
|
|
HttpResponse.__init__(self)
|
2006-06-20 12:06:16 +08:00
|
|
|
self['Location'] = quote(redirect_to, safe=RESERVED_CHARS)
|
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):
|
|
|
|
HttpResponse.__init__(self)
|
2006-06-20 12:06:16 +08:00
|
|
|
self['Location'] = quote(redirect_to, safe=RESERVED_CHARS)
|
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):
|
|
|
|
HttpResponse.__init__(self)
|
|
|
|
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-09-01 13:01:47 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
HttpResponse.__init__(self, *args, **kwargs)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
class HttpResponseServerError(HttpResponse):
|
2007-03-30 14:46:36 +08:00
|
|
|
status_code = 500
|
|
|
|
|
2005-09-01 13:01:47 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
HttpResponse.__init__(self, *args, **kwargs)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
def get_host(request):
|
2006-06-20 11:48:31 +08:00
|
|
|
"Gets the HTTP host from the environment or request headers."
|
2006-05-02 09:31:56 +08:00
|
|
|
host = request.META.get('HTTP_X_FORWARDED_HOST', '')
|
|
|
|
if not host:
|
|
|
|
host = request.META.get('HTTP_HOST', '')
|
|
|
|
return host
|