PageRenderTime 54ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/site-packages/django/http/__init__.py

http://github.com/JetBrains/intellij-community
Python | 660 lines | 637 code | 13 blank | 10 comment | 14 complexity | 17f9249fe523d43264f422544edd444a MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0
  1. import datetime
  2. import os
  3. import re
  4. import time
  5. from pprint import pformat
  6. from urllib import urlencode, quote
  7. from urlparse import urljoin
  8. try:
  9. from cStringIO import StringIO
  10. except ImportError:
  11. from StringIO import StringIO
  12. try:
  13. # The mod_python version is more efficient, so try importing it first.
  14. from mod_python.util import parse_qsl
  15. except ImportError:
  16. try:
  17. # Python 2.6 and greater
  18. from urlparse import parse_qsl
  19. except ImportError:
  20. # Python 2.5, 2.4. Works on Python 2.6 but raises
  21. # PendingDeprecationWarning
  22. from cgi import parse_qsl
  23. # httponly support exists in Python 2.6's Cookie library,
  24. # but not in Python 2.4 or 2.5.
  25. import Cookie
  26. if Cookie.Morsel._reserved.has_key('httponly'):
  27. SimpleCookie = Cookie.SimpleCookie
  28. else:
  29. class Morsel(Cookie.Morsel):
  30. def __setitem__(self, K, V):
  31. K = K.lower()
  32. if K == "httponly":
  33. if V:
  34. # The superclass rejects httponly as a key,
  35. # so we jump to the grandparent.
  36. super(Cookie.Morsel, self).__setitem__(K, V)
  37. else:
  38. super(Morsel, self).__setitem__(K, V)
  39. def OutputString(self, attrs=None):
  40. output = super(Morsel, self).OutputString(attrs)
  41. if "httponly" in self:
  42. output += "; httponly"
  43. return output
  44. class SimpleCookie(Cookie.SimpleCookie):
  45. def __set(self, key, real_value, coded_value):
  46. M = self.get(key, Morsel())
  47. M.set(key, real_value, coded_value)
  48. dict.__setitem__(self, key, M)
  49. def __setitem__(self, key, value):
  50. rval, cval = self.value_encode(value)
  51. self.__set(key, rval, cval)
  52. from django.utils.datastructures import MultiValueDict, ImmutableList
  53. from django.utils.encoding import smart_str, iri_to_uri, force_unicode
  54. from django.utils.http import cookie_date
  55. from django.http.multipartparser import MultiPartParser
  56. from django.conf import settings
  57. from django.core.files import uploadhandler
  58. from utils import *
  59. RESERVED_CHARS="!*'();:@&=+$,/?%#[]"
  60. absolute_http_url_re = re.compile(r"^https?://", re.I)
  61. class Http404(Exception):
  62. pass
  63. class HttpRequest(object):
  64. """A basic HTTP request."""
  65. # The encoding used in GET/POST dicts. None means use default setting.
  66. _encoding = None
  67. _upload_handlers = []
  68. def __init__(self):
  69. self.GET, self.POST, self.COOKIES, self.META, self.FILES = {}, {}, {}, {}, {}
  70. self.path = ''
  71. self.path_info = ''
  72. self.method = None
  73. def __repr__(self):
  74. return '<HttpRequest\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % \
  75. (pformat(self.GET), pformat(self.POST), pformat(self.COOKIES),
  76. pformat(self.META))
  77. def get_host(self):
  78. """Returns the HTTP host using the environment or request headers."""
  79. # We try three options, in order of decreasing preference.
  80. if 'HTTP_X_FORWARDED_HOST' in self.META:
  81. host = self.META['HTTP_X_FORWARDED_HOST']
  82. elif 'HTTP_HOST' in self.META:
  83. host = self.META['HTTP_HOST']
  84. else:
  85. # Reconstruct the host using the algorithm from PEP 333.
  86. host = self.META['SERVER_NAME']
  87. server_port = str(self.META['SERVER_PORT'])
  88. if server_port != (self.is_secure() and '443' or '80'):
  89. host = '%s:%s' % (host, server_port)
  90. return host
  91. def get_full_path(self):
  92. return ''
  93. def build_absolute_uri(self, location=None):
  94. """
  95. Builds an absolute URI from the location and the variables available in
  96. this request. If no location is specified, the absolute URI is built on
  97. ``request.get_full_path()``.
  98. """
  99. if not location:
  100. location = self.get_full_path()
  101. if not absolute_http_url_re.match(location):
  102. current_uri = '%s://%s%s' % (self.is_secure() and 'https' or 'http',
  103. self.get_host(), self.path)
  104. location = urljoin(current_uri, location)
  105. return iri_to_uri(location)
  106. def is_secure(self):
  107. return os.environ.get("HTTPS") == "on"
  108. def is_ajax(self):
  109. return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
  110. def _set_encoding(self, val):
  111. """
  112. Sets the encoding used for GET/POST accesses. If the GET or POST
  113. dictionary has already been created, it is removed and recreated on the
  114. next access (so that it is decoded correctly).
  115. """
  116. self._encoding = val
  117. if hasattr(self, '_get'):
  118. del self._get
  119. if hasattr(self, '_post'):
  120. del self._post
  121. def _get_encoding(self):
  122. return self._encoding
  123. encoding = property(_get_encoding, _set_encoding)
  124. def _initialize_handlers(self):
  125. self._upload_handlers = [uploadhandler.load_handler(handler, self)
  126. for handler in settings.FILE_UPLOAD_HANDLERS]
  127. def _set_upload_handlers(self, upload_handlers):
  128. if hasattr(self, '_files'):
  129. raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
  130. self._upload_handlers = upload_handlers
  131. def _get_upload_handlers(self):
  132. if not self._upload_handlers:
  133. # If thre are no upload handlers defined, initialize them from settings.
  134. self._initialize_handlers()
  135. return self._upload_handlers
  136. upload_handlers = property(_get_upload_handlers, _set_upload_handlers)
  137. def parse_file_upload(self, META, post_data):
  138. """Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
  139. self.upload_handlers = ImmutableList(
  140. self.upload_handlers,
  141. warning = "You cannot alter upload handlers after the upload has been processed."
  142. )
  143. parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
  144. return parser.parse()
  145. def _get_raw_post_data(self):
  146. if not hasattr(self, '_raw_post_data'):
  147. if self._read_started:
  148. raise Exception("You cannot access raw_post_data after reading from request's data stream")
  149. try:
  150. content_length = int(self.META.get('CONTENT_LENGTH', 0))
  151. except (ValueError, TypeError):
  152. # If CONTENT_LENGTH was empty string or not an integer, don't
  153. # error out. We've also seen None passed in here (against all
  154. # specs, but see ticket #8259), so we handle TypeError as well.
  155. content_length = 0
  156. if content_length:
  157. self._raw_post_data = self.read(content_length)
  158. else:
  159. self._raw_post_data = self.read()
  160. self._stream = StringIO(self._raw_post_data)
  161. return self._raw_post_data
  162. raw_post_data = property(_get_raw_post_data)
  163. def _mark_post_parse_error(self):
  164. self._post = QueryDict('')
  165. self._files = MultiValueDict()
  166. self._post_parse_error = True
  167. def _load_post_and_files(self):
  168. # Populates self._post and self._files
  169. if self.method != 'POST':
  170. self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()
  171. return
  172. if self._read_started:
  173. self._mark_post_parse_error()
  174. return
  175. if self.META.get('CONTENT_TYPE', '').startswith('multipart'):
  176. self._raw_post_data = ''
  177. try:
  178. self._post, self._files = self.parse_file_upload(self.META, self)
  179. except:
  180. # An error occured while parsing POST data. Since when
  181. # formatting the error the request handler might access
  182. # self.POST, set self._post and self._file to prevent
  183. # attempts to parse POST data again.
  184. # Mark that an error occured. This allows self.__repr__ to
  185. # be explicit about it instead of simply representing an
  186. # empty POST
  187. self._mark_post_parse_error()
  188. raise
  189. else:
  190. self._post, self._files = QueryDict(self.raw_post_data, encoding=self._encoding), MultiValueDict()
  191. ## File-like and iterator interface.
  192. ##
  193. ## Expects self._stream to be set to an appropriate source of bytes by
  194. ## a corresponding request subclass (WSGIRequest or ModPythonRequest).
  195. ## Also when request data has already been read by request.POST or
  196. ## request.raw_post_data, self._stream points to a StringIO instance
  197. ## containing that data.
  198. def read(self, *args, **kwargs):
  199. self._read_started = True
  200. return self._stream.read(*args, **kwargs)
  201. def readline(self, *args, **kwargs):
  202. self._read_started = True
  203. return self._stream.readline(*args, **kwargs)
  204. def xreadlines(self):
  205. while True:
  206. buf = self.readline()
  207. if not buf:
  208. break
  209. yield buf
  210. __iter__ = xreadlines
  211. def readlines(self):
  212. return list(iter(self))
  213. class QueryDict(MultiValueDict):
  214. """
  215. A specialized MultiValueDict that takes a query string when initialized.
  216. This is immutable unless you create a copy of it.
  217. Values retrieved from this class are converted from the given encoding
  218. (DEFAULT_CHARSET by default) to unicode.
  219. """
  220. # These are both reset in __init__, but is specified here at the class
  221. # level so that unpickling will have valid values
  222. _mutable = True
  223. _encoding = None
  224. def __init__(self, query_string, mutable=False, encoding=None):
  225. MultiValueDict.__init__(self)
  226. if not encoding:
  227. # *Important*: do not import settings any earlier because of note
  228. # in core.handlers.modpython.
  229. from django.conf import settings
  230. encoding = settings.DEFAULT_CHARSET
  231. self.encoding = encoding
  232. for key, value in parse_qsl((query_string or ''), True): # keep_blank_values=True
  233. self.appendlist(force_unicode(key, encoding, errors='replace'),
  234. force_unicode(value, encoding, errors='replace'))
  235. self._mutable = mutable
  236. def _get_encoding(self):
  237. if self._encoding is None:
  238. # *Important*: do not import settings at the module level because
  239. # of the note in core.handlers.modpython.
  240. from django.conf import settings
  241. self._encoding = settings.DEFAULT_CHARSET
  242. return self._encoding
  243. def _set_encoding(self, value):
  244. self._encoding = value
  245. encoding = property(_get_encoding, _set_encoding)
  246. def _assert_mutable(self):
  247. if not self._mutable:
  248. raise AttributeError("This QueryDict instance is immutable")
  249. def __setitem__(self, key, value):
  250. self._assert_mutable()
  251. key = str_to_unicode(key, self.encoding)
  252. value = str_to_unicode(value, self.encoding)
  253. MultiValueDict.__setitem__(self, key, value)
  254. def __delitem__(self, key):
  255. self._assert_mutable()
  256. super(QueryDict, self).__delitem__(key)
  257. def __copy__(self):
  258. result = self.__class__('', mutable=True, encoding=self.encoding)
  259. for key, value in dict.items(self):
  260. dict.__setitem__(result, key, value)
  261. return result
  262. def __deepcopy__(self, memo):
  263. import django.utils.copycompat as copy
  264. result = self.__class__('', mutable=True, encoding=self.encoding)
  265. memo[id(self)] = result
  266. for key, value in dict.items(self):
  267. dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo))
  268. return result
  269. def setlist(self, key, list_):
  270. self._assert_mutable()
  271. key = str_to_unicode(key, self.encoding)
  272. list_ = [str_to_unicode(elt, self.encoding) for elt in list_]
  273. MultiValueDict.setlist(self, key, list_)
  274. def setlistdefault(self, key, default_list=()):
  275. self._assert_mutable()
  276. if key not in self:
  277. self.setlist(key, default_list)
  278. return MultiValueDict.getlist(self, key)
  279. def appendlist(self, key, value):
  280. self._assert_mutable()
  281. key = str_to_unicode(key, self.encoding)
  282. value = str_to_unicode(value, self.encoding)
  283. MultiValueDict.appendlist(self, key, value)
  284. def update(self, other_dict):
  285. self._assert_mutable()
  286. f = lambda s: str_to_unicode(s, self.encoding)
  287. if hasattr(other_dict, 'lists'):
  288. for key, valuelist in other_dict.lists():
  289. for value in valuelist:
  290. MultiValueDict.update(self, {f(key): f(value)})
  291. else:
  292. d = dict([(f(k), f(v)) for k, v in other_dict.items()])
  293. MultiValueDict.update(self, d)
  294. def pop(self, key, *args):
  295. self._assert_mutable()
  296. return MultiValueDict.pop(self, key, *args)
  297. def popitem(self):
  298. self._assert_mutable()
  299. return MultiValueDict.popitem(self)
  300. def clear(self):
  301. self._assert_mutable()
  302. MultiValueDict.clear(self)
  303. def setdefault(self, key, default=None):
  304. self._assert_mutable()
  305. key = str_to_unicode(key, self.encoding)
  306. default = str_to_unicode(default, self.encoding)
  307. return MultiValueDict.setdefault(self, key, default)
  308. def copy(self):
  309. """Returns a mutable copy of this object."""
  310. return self.__deepcopy__({})
  311. def urlencode(self, safe=None):
  312. """
  313. Returns an encoded string of all query string arguments.
  314. :arg safe: Used to specify characters which do not require quoting, for
  315. example::
  316. >>> q = QueryDict('', mutable=True)
  317. >>> q['next'] = '/a&b/'
  318. >>> q.urlencode()
  319. 'next=%2Fa%26b%2F'
  320. >>> q.urlencode(safe='/')
  321. 'next=/a%26b/'
  322. """
  323. output = []
  324. if safe:
  325. encode = lambda k, v: '%s=%s' % ((quote(k, safe), quote(v, safe)))
  326. else:
  327. encode = lambda k, v: urlencode({k: v})
  328. for k, list_ in self.lists():
  329. k = smart_str(k, self.encoding)
  330. output.extend([encode(k, smart_str(v, self.encoding))
  331. for v in list_])
  332. return '&'.join(output)
  333. class CompatCookie(SimpleCookie):
  334. """
  335. Cookie class that handles some issues with browser compatibility.
  336. """
  337. def value_encode(self, val):
  338. # Some browsers do not support quoted-string from RFC 2109,
  339. # including some versions of Safari and Internet Explorer.
  340. # These browsers split on ';', and some versions of Safari
  341. # are known to split on ', '. Therefore, we encode ';' and ','
  342. # SimpleCookie already does the hard work of encoding and decoding.
  343. # It uses octal sequences like '\\012' for newline etc.
  344. # and non-ASCII chars. We just make use of this mechanism, to
  345. # avoid introducing two encoding schemes which would be confusing
  346. # and especially awkward for javascript.
  347. # NB, contrary to Python docs, value_encode returns a tuple containing
  348. # (real val, encoded_val)
  349. val, encoded = super(CompatCookie, self).value_encode(val)
  350. encoded = encoded.replace(";", "\\073").replace(",","\\054")
  351. # If encoded now contains any quoted chars, we need double quotes
  352. # around the whole string.
  353. if "\\" in encoded and not encoded.startswith('"'):
  354. encoded = '"' + encoded + '"'
  355. return val, encoded
  356. def parse_cookie(cookie):
  357. if cookie == '':
  358. return {}
  359. if not isinstance(cookie, Cookie.BaseCookie):
  360. try:
  361. c = CompatCookie()
  362. c.load(cookie)
  363. except Cookie.CookieError:
  364. # Invalid cookie
  365. return {}
  366. else:
  367. c = cookie
  368. cookiedict = {}
  369. for key in c.keys():
  370. cookiedict[key] = c.get(key).value
  371. return cookiedict
  372. class BadHeaderError(ValueError):
  373. pass
  374. class HttpResponse(object):
  375. """A basic HTTP response, with content and dictionary-accessed headers."""
  376. status_code = 200
  377. def __init__(self, content='', mimetype=None, status=None,
  378. content_type=None):
  379. # _headers is a mapping of the lower-case name to the original case of
  380. # the header (required for working with legacy systems) and the header
  381. # value. Both the name of the header and its value are ASCII strings.
  382. self._headers = {}
  383. self._charset = settings.DEFAULT_CHARSET
  384. if mimetype:
  385. content_type = mimetype # For backwards compatibility
  386. if not content_type:
  387. content_type = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE,
  388. self._charset)
  389. if not isinstance(content, basestring) and hasattr(content, '__iter__'):
  390. self._container = content
  391. self._is_string = False
  392. else:
  393. self._container = [content]
  394. self._is_string = True
  395. self.cookies = CompatCookie()
  396. if status:
  397. self.status_code = status
  398. self['Content-Type'] = content_type
  399. def __str__(self):
  400. """Full HTTP message, including headers."""
  401. return '\n'.join(['%s: %s' % (key, value)
  402. for key, value in self._headers.values()]) \
  403. + '\n\n' + self.content
  404. def _convert_to_ascii(self, *values):
  405. """Converts all values to ascii strings."""
  406. for value in values:
  407. if isinstance(value, unicode):
  408. try:
  409. value = value.encode('us-ascii')
  410. except UnicodeError, e:
  411. e.reason += ', HTTP response headers must be in US-ASCII format'
  412. raise
  413. else:
  414. value = str(value)
  415. if '\n' in value or '\r' in value:
  416. raise BadHeaderError("Header values can't contain newlines (got %r)" % (value))
  417. yield value
  418. def __setitem__(self, header, value):
  419. header, value = self._convert_to_ascii(header, value)
  420. self._headers[header.lower()] = (header, value)
  421. def __delitem__(self, header):
  422. try:
  423. del self._headers[header.lower()]
  424. except KeyError:
  425. pass
  426. def __getitem__(self, header):
  427. return self._headers[header.lower()][1]
  428. def has_header(self, header):
  429. """Case-insensitive check for a header."""
  430. return self._headers.has_key(header.lower())
  431. __contains__ = has_header
  432. def items(self):
  433. return self._headers.values()
  434. def get(self, header, alternate):
  435. return self._headers.get(header.lower(), (None, alternate))[1]
  436. def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
  437. domain=None, secure=False, httponly=False):
  438. """
  439. Sets a cookie.
  440. ``expires`` can be a string in the correct format or a
  441. ``datetime.datetime`` object in UTC. If ``expires`` is a datetime
  442. object then ``max_age`` will be calculated.
  443. """
  444. self.cookies[key] = value
  445. if expires is not None:
  446. if isinstance(expires, datetime.datetime):
  447. delta = expires - expires.utcnow()
  448. # Add one second so the date matches exactly (a fraction of
  449. # time gets lost between converting to a timedelta and
  450. # then the date string).
  451. delta = delta + datetime.timedelta(seconds=1)
  452. # Just set max_age - the max_age logic will set expires.
  453. expires = None
  454. max_age = max(0, delta.days * 86400 + delta.seconds)
  455. else:
  456. self.cookies[key]['expires'] = expires
  457. if max_age is not None:
  458. self.cookies[key]['max-age'] = max_age
  459. # IE requires expires, so set it if hasn't been already.
  460. if not expires:
  461. self.cookies[key]['expires'] = cookie_date(time.time() +
  462. max_age)
  463. if path is not None:
  464. self.cookies[key]['path'] = path
  465. if domain is not None:
  466. self.cookies[key]['domain'] = domain
  467. if secure:
  468. self.cookies[key]['secure'] = True
  469. if httponly:
  470. self.cookies[key]['httponly'] = True
  471. def delete_cookie(self, key, path='/', domain=None):
  472. self.set_cookie(key, max_age=0, path=path, domain=domain,
  473. expires='Thu, 01-Jan-1970 00:00:00 GMT')
  474. def _get_content(self):
  475. if self.has_header('Content-Encoding'):
  476. return ''.join(self._container)
  477. return smart_str(''.join(self._container), self._charset)
  478. def _set_content(self, value):
  479. self._container = [value]
  480. self._is_string = True
  481. content = property(_get_content, _set_content)
  482. def __iter__(self):
  483. self._iterator = iter(self._container)
  484. return self
  485. def next(self):
  486. chunk = self._iterator.next()
  487. if isinstance(chunk, unicode):
  488. chunk = chunk.encode(self._charset)
  489. return str(chunk)
  490. def close(self):
  491. if hasattr(self._container, 'close'):
  492. self._container.close()
  493. # The remaining methods partially implement the file-like object interface.
  494. # See http://docs.python.org/lib/bltin-file-objects.html
  495. def write(self, content):
  496. if not self._is_string:
  497. raise Exception("This %s instance is not writable" % self.__class__)
  498. self._container.append(content)
  499. def flush(self):
  500. pass
  501. def tell(self):
  502. if not self._is_string:
  503. raise Exception("This %s instance cannot tell its position" % self.__class__)
  504. return sum([len(chunk) for chunk in self._container])
  505. class HttpResponseRedirect(HttpResponse):
  506. status_code = 302
  507. def __init__(self, redirect_to):
  508. HttpResponse.__init__(self)
  509. self['Location'] = iri_to_uri(redirect_to)
  510. class HttpResponsePermanentRedirect(HttpResponse):
  511. status_code = 301
  512. def __init__(self, redirect_to):
  513. HttpResponse.__init__(self)
  514. self['Location'] = iri_to_uri(redirect_to)
  515. class HttpResponseNotModified(HttpResponse):
  516. status_code = 304
  517. class HttpResponseBadRequest(HttpResponse):
  518. status_code = 400
  519. class HttpResponseNotFound(HttpResponse):
  520. status_code = 404
  521. class HttpResponseForbidden(HttpResponse):
  522. status_code = 403
  523. class HttpResponseNotAllowed(HttpResponse):
  524. status_code = 405
  525. def __init__(self, permitted_methods):
  526. HttpResponse.__init__(self)
  527. self['Allow'] = ', '.join(permitted_methods)
  528. class HttpResponseGone(HttpResponse):
  529. status_code = 410
  530. def __init__(self, *args, **kwargs):
  531. HttpResponse.__init__(self, *args, **kwargs)
  532. class HttpResponseServerError(HttpResponse):
  533. status_code = 500
  534. def __init__(self, *args, **kwargs):
  535. HttpResponse.__init__(self, *args, **kwargs)
  536. # A backwards compatible alias for HttpRequest.get_host.
  537. def get_host(request):
  538. return request.get_host()
  539. # It's neither necessary nor appropriate to use
  540. # django.utils.encoding.smart_unicode for parsing URLs and form inputs. Thus,
  541. # this slightly more restricted function.
  542. def str_to_unicode(s, encoding):
  543. """
  544. Converts basestring objects to unicode, using the given encoding. Illegally
  545. encoded input characters are replaced with Unicode "unknown" codepoint
  546. (\ufffd).
  547. Returns any non-basestring objects without change.
  548. """
  549. if isinstance(s, str):
  550. return unicode(s, encoding, 'replace')
  551. else:
  552. return s