PageRenderTime 56ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/django/http/__init__.py

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