/django/http/__init__.py

https://code.google.com/p/mango-py/ · Python · 699 lines · 506 code · 91 blank · 102 comment · 90 complexity · e47e1ab67c46a94b52dac0fb5aebe2b3 MD5 · raw file

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