You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2028 lines
82 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.wrappers
  4. ~~~~~~~~~~~~~~~~~
  5. The wrappers are simple request and response objects which you can
  6. subclass to do whatever you want them to do. The request object contains
  7. the information transmitted by the client (webbrowser) and the response
  8. object contains all the information sent back to the browser.
  9. An important detail is that the request object is created with the WSGI
  10. environ and will act as high-level proxy whereas the response object is an
  11. actual WSGI application.
  12. Like everything else in Werkzeug these objects will work correctly with
  13. unicode data. Incoming form data parsed by the response object will be
  14. decoded into an unicode object if possible and if it makes sense.
  15. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  16. :license: BSD, see LICENSE for more details.
  17. """
  18. from functools import update_wrapper
  19. from datetime import datetime, timedelta
  20. from warnings import warn
  21. from werkzeug.http import HTTP_STATUS_CODES, \
  22. parse_accept_header, parse_cache_control_header, parse_etags, \
  23. parse_date, generate_etag, is_resource_modified, unquote_etag, \
  24. quote_etag, parse_set_header, parse_authorization_header, \
  25. parse_www_authenticate_header, remove_entity_headers, \
  26. parse_options_header, dump_options_header, http_date, \
  27. parse_if_range_header, parse_cookie, dump_cookie, \
  28. parse_range_header, parse_content_range_header, dump_header, \
  29. parse_age, dump_age
  30. from werkzeug.urls import url_decode, iri_to_uri, url_join
  31. from werkzeug.formparser import FormDataParser, default_stream_factory
  32. from werkzeug.utils import cached_property, environ_property, \
  33. header_property, get_content_type
  34. from werkzeug.wsgi import get_current_url, get_host, \
  35. ClosingIterator, get_input_stream, get_content_length, _RangeWrapper
  36. from werkzeug.datastructures import MultiDict, CombinedMultiDict, Headers, \
  37. EnvironHeaders, ImmutableMultiDict, ImmutableTypeConversionDict, \
  38. ImmutableList, MIMEAccept, CharsetAccept, LanguageAccept, \
  39. ResponseCacheControl, RequestCacheControl, CallbackDict, \
  40. ContentRange, iter_multi_items
  41. from werkzeug._internal import _get_environ
  42. from werkzeug._compat import to_bytes, string_types, text_type, \
  43. integer_types, wsgi_decoding_dance, wsgi_get_bytes, \
  44. to_unicode, to_native, BytesIO
  45. def _run_wsgi_app(*args):
  46. """This function replaces itself to ensure that the test module is not
  47. imported unless required. DO NOT USE!
  48. """
  49. global _run_wsgi_app
  50. from werkzeug.test import run_wsgi_app as _run_wsgi_app
  51. return _run_wsgi_app(*args)
  52. def _warn_if_string(iterable):
  53. """Helper for the response objects to check if the iterable returned
  54. to the WSGI server is not a string.
  55. """
  56. if isinstance(iterable, string_types):
  57. warn(Warning('response iterable was set to a string. This appears '
  58. 'to work but means that the server will send the '
  59. 'data to the client char, by char. This is almost '
  60. 'never intended behavior, use response.data to assign '
  61. 'strings to the response object.'), stacklevel=2)
  62. def _assert_not_shallow(request):
  63. if request.shallow:
  64. raise RuntimeError('A shallow request tried to consume '
  65. 'form data. If you really want to do '
  66. 'that, set `shallow` to False.')
  67. def _iter_encoded(iterable, charset):
  68. for item in iterable:
  69. if isinstance(item, text_type):
  70. yield item.encode(charset)
  71. else:
  72. yield item
  73. def _clean_accept_ranges(accept_ranges):
  74. if accept_ranges is True:
  75. return "bytes"
  76. elif accept_ranges is False:
  77. return "none"
  78. elif isinstance(accept_ranges, text_type):
  79. return to_native(accept_ranges)
  80. raise ValueError("Invalid accept_ranges value")
  81. class BaseRequest(object):
  82. """Very basic request object. This does not implement advanced stuff like
  83. entity tag parsing or cache controls. The request object is created with
  84. the WSGI environment as first argument and will add itself to the WSGI
  85. environment as ``'werkzeug.request'`` unless it's created with
  86. `populate_request` set to False.
  87. There are a couple of mixins available that add additional functionality
  88. to the request object, there is also a class called `Request` which
  89. subclasses `BaseRequest` and all the important mixins.
  90. It's a good idea to create a custom subclass of the :class:`BaseRequest`
  91. and add missing functionality either via mixins or direct implementation.
  92. Here an example for such subclasses::
  93. from werkzeug.wrappers import BaseRequest, ETagRequestMixin
  94. class Request(BaseRequest, ETagRequestMixin):
  95. pass
  96. Request objects are **read only**. As of 0.5 modifications are not
  97. allowed in any place. Unlike the lower level parsing functions the
  98. request object will use immutable objects everywhere possible.
  99. Per default the request object will assume all the text data is `utf-8`
  100. encoded. Please refer to `the unicode chapter <unicode.txt>`_ for more
  101. details about customizing the behavior.
  102. Per default the request object will be added to the WSGI
  103. environment as `werkzeug.request` to support the debugging system.
  104. If you don't want that, set `populate_request` to `False`.
  105. If `shallow` is `True` the environment is initialized as shallow
  106. object around the environ. Every operation that would modify the
  107. environ in any way (such as consuming form data) raises an exception
  108. unless the `shallow` attribute is explicitly set to `False`. This
  109. is useful for middlewares where you don't want to consume the form
  110. data by accident. A shallow request is not populated to the WSGI
  111. environment.
  112. .. versionchanged:: 0.5
  113. read-only mode was enforced by using immutables classes for all
  114. data.
  115. """
  116. #: the charset for the request, defaults to utf-8
  117. charset = 'utf-8'
  118. #: the error handling procedure for errors, defaults to 'replace'
  119. encoding_errors = 'replace'
  120. #: the maximum content length. This is forwarded to the form data
  121. #: parsing function (:func:`parse_form_data`). When set and the
  122. #: :attr:`form` or :attr:`files` attribute is accessed and the
  123. #: parsing fails because more than the specified value is transmitted
  124. #: a :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised.
  125. #:
  126. #: Have a look at :ref:`dealing-with-request-data` for more details.
  127. #:
  128. #: .. versionadded:: 0.5
  129. max_content_length = None
  130. #: the maximum form field size. This is forwarded to the form data
  131. #: parsing function (:func:`parse_form_data`). When set and the
  132. #: :attr:`form` or :attr:`files` attribute is accessed and the
  133. #: data in memory for post data is longer than the specified value a
  134. #: :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised.
  135. #:
  136. #: Have a look at :ref:`dealing-with-request-data` for more details.
  137. #:
  138. #: .. versionadded:: 0.5
  139. max_form_memory_size = None
  140. #: the class to use for `args` and `form`. The default is an
  141. #: :class:`~werkzeug.datastructures.ImmutableMultiDict` which supports
  142. #: multiple values per key. alternatively it makes sense to use an
  143. #: :class:`~werkzeug.datastructures.ImmutableOrderedMultiDict` which
  144. #: preserves order or a :class:`~werkzeug.datastructures.ImmutableDict`
  145. #: which is the fastest but only remembers the last key. It is also
  146. #: possible to use mutable structures, but this is not recommended.
  147. #:
  148. #: .. versionadded:: 0.6
  149. parameter_storage_class = ImmutableMultiDict
  150. #: the type to be used for list values from the incoming WSGI environment.
  151. #: By default an :class:`~werkzeug.datastructures.ImmutableList` is used
  152. #: (for example for :attr:`access_list`).
  153. #:
  154. #: .. versionadded:: 0.6
  155. list_storage_class = ImmutableList
  156. #: the type to be used for dict values from the incoming WSGI environment.
  157. #: By default an
  158. #: :class:`~werkzeug.datastructures.ImmutableTypeConversionDict` is used
  159. #: (for example for :attr:`cookies`).
  160. #:
  161. #: .. versionadded:: 0.6
  162. dict_storage_class = ImmutableTypeConversionDict
  163. #: The form data parser that shoud be used. Can be replaced to customize
  164. #: the form date parsing.
  165. form_data_parser_class = FormDataParser
  166. #: Optionally a list of hosts that is trusted by this request. By default
  167. #: all hosts are trusted which means that whatever the client sends the
  168. #: host is will be accepted.
  169. #:
  170. #: This is the recommended setup as a webserver should manually be set up
  171. #: to only route correct hosts to the application, and remove the
  172. #: `X-Forwarded-Host` header if it is not being used (see
  173. #: :func:`werkzeug.wsgi.get_host`).
  174. #:
  175. #: .. versionadded:: 0.9
  176. trusted_hosts = None
  177. #: Indicates whether the data descriptor should be allowed to read and
  178. #: buffer up the input stream. By default it's enabled.
  179. #:
  180. #: .. versionadded:: 0.9
  181. disable_data_descriptor = False
  182. def __init__(self, environ, populate_request=True, shallow=False):
  183. self.environ = environ
  184. if populate_request and not shallow:
  185. self.environ['werkzeug.request'] = self
  186. self.shallow = shallow
  187. def __repr__(self):
  188. # make sure the __repr__ even works if the request was created
  189. # from an invalid WSGI environment. If we display the request
  190. # in a debug session we don't want the repr to blow up.
  191. args = []
  192. try:
  193. args.append("'%s'" % to_native(self.url, self.url_charset))
  194. args.append('[%s]' % self.method)
  195. except Exception:
  196. args.append('(invalid WSGI environ)')
  197. return '<%s %s>' % (
  198. self.__class__.__name__,
  199. ' '.join(args)
  200. )
  201. @property
  202. def url_charset(self):
  203. """The charset that is assumed for URLs. Defaults to the value
  204. of :attr:`charset`.
  205. .. versionadded:: 0.6
  206. """
  207. return self.charset
  208. @classmethod
  209. def from_values(cls, *args, **kwargs):
  210. """Create a new request object based on the values provided. If
  211. environ is given missing values are filled from there. This method is
  212. useful for small scripts when you need to simulate a request from an URL.
  213. Do not use this method for unittesting, there is a full featured client
  214. object (:class:`Client`) that allows to create multipart requests,
  215. support for cookies etc.
  216. This accepts the same options as the
  217. :class:`~werkzeug.test.EnvironBuilder`.
  218. .. versionchanged:: 0.5
  219. This method now accepts the same arguments as
  220. :class:`~werkzeug.test.EnvironBuilder`. Because of this the
  221. `environ` parameter is now called `environ_overrides`.
  222. :return: request object
  223. """
  224. from werkzeug.test import EnvironBuilder
  225. charset = kwargs.pop('charset', cls.charset)
  226. kwargs['charset'] = charset
  227. builder = EnvironBuilder(*args, **kwargs)
  228. try:
  229. return builder.get_request(cls)
  230. finally:
  231. builder.close()
  232. @classmethod
  233. def application(cls, f):
  234. """Decorate a function as responder that accepts the request as first
  235. argument. This works like the :func:`responder` decorator but the
  236. function is passed the request object as first argument and the
  237. request object will be closed automatically::
  238. @Request.application
  239. def my_wsgi_app(request):
  240. return Response('Hello World!')
  241. As of Werkzeug 0.14 HTTP exceptions are automatically caught and
  242. converted to responses instead of failing.
  243. :param f: the WSGI callable to decorate
  244. :return: a new WSGI callable
  245. """
  246. #: return a callable that wraps the -2nd argument with the request
  247. #: and calls the function with all the arguments up to that one and
  248. #: the request. The return value is then called with the latest
  249. #: two arguments. This makes it possible to use this decorator for
  250. #: both methods and standalone WSGI functions.
  251. from werkzeug.exceptions import HTTPException
  252. def application(*args):
  253. request = cls(args[-2])
  254. with request:
  255. try:
  256. resp = f(*args[:-2] + (request,))
  257. except HTTPException as e:
  258. resp = e.get_response(args[-2])
  259. return resp(*args[-2:])
  260. return update_wrapper(application, f)
  261. def _get_file_stream(self, total_content_length, content_type, filename=None,
  262. content_length=None):
  263. """Called to get a stream for the file upload.
  264. This must provide a file-like class with `read()`, `readline()`
  265. and `seek()` methods that is both writeable and readable.
  266. The default implementation returns a temporary file if the total
  267. content length is higher than 500KB. Because many browsers do not
  268. provide a content length for the files only the total content
  269. length matters.
  270. :param total_content_length: the total content length of all the
  271. data in the request combined. This value
  272. is guaranteed to be there.
  273. :param content_type: the mimetype of the uploaded file.
  274. :param filename: the filename of the uploaded file. May be `None`.
  275. :param content_length: the length of this file. This value is usually
  276. not provided because webbrowsers do not provide
  277. this value.
  278. """
  279. return default_stream_factory(
  280. total_content_length=total_content_length,
  281. content_type=content_type,
  282. filename=filename,
  283. content_length=content_length)
  284. @property
  285. def want_form_data_parsed(self):
  286. """Returns True if the request method carries content. As of
  287. Werkzeug 0.9 this will be the case if a content type is transmitted.
  288. .. versionadded:: 0.8
  289. """
  290. return bool(self.environ.get('CONTENT_TYPE'))
  291. def make_form_data_parser(self):
  292. """Creates the form data parser. Instantiates the
  293. :attr:`form_data_parser_class` with some parameters.
  294. .. versionadded:: 0.8
  295. """
  296. return self.form_data_parser_class(self._get_file_stream,
  297. self.charset,
  298. self.encoding_errors,
  299. self.max_form_memory_size,
  300. self.max_content_length,
  301. self.parameter_storage_class)
  302. def _load_form_data(self):
  303. """Method used internally to retrieve submitted data. After calling
  304. this sets `form` and `files` on the request object to multi dicts
  305. filled with the incoming form data. As a matter of fact the input
  306. stream will be empty afterwards. You can also call this method to
  307. force the parsing of the form data.
  308. .. versionadded:: 0.8
  309. """
  310. # abort early if we have already consumed the stream
  311. if 'form' in self.__dict__:
  312. return
  313. _assert_not_shallow(self)
  314. if self.want_form_data_parsed:
  315. content_type = self.environ.get('CONTENT_TYPE', '')
  316. content_length = get_content_length(self.environ)
  317. mimetype, options = parse_options_header(content_type)
  318. parser = self.make_form_data_parser()
  319. data = parser.parse(self._get_stream_for_parsing(),
  320. mimetype, content_length, options)
  321. else:
  322. data = (self.stream, self.parameter_storage_class(),
  323. self.parameter_storage_class())
  324. # inject the values into the instance dict so that we bypass
  325. # our cached_property non-data descriptor.
  326. d = self.__dict__
  327. d['stream'], d['form'], d['files'] = data
  328. def _get_stream_for_parsing(self):
  329. """This is the same as accessing :attr:`stream` with the difference
  330. that if it finds cached data from calling :meth:`get_data` first it
  331. will create a new stream out of the cached data.
  332. .. versionadded:: 0.9.3
  333. """
  334. cached_data = getattr(self, '_cached_data', None)
  335. if cached_data is not None:
  336. return BytesIO(cached_data)
  337. return self.stream
  338. def close(self):
  339. """Closes associated resources of this request object. This
  340. closes all file handles explicitly. You can also use the request
  341. object in a with statement which will automatically close it.
  342. .. versionadded:: 0.9
  343. """
  344. files = self.__dict__.get('files')
  345. for key, value in iter_multi_items(files or ()):
  346. value.close()
  347. def __enter__(self):
  348. return self
  349. def __exit__(self, exc_type, exc_value, tb):
  350. self.close()
  351. @cached_property
  352. def stream(self):
  353. """
  354. If the incoming form data was not encoded with a known mimetype
  355. the data is stored unmodified in this stream for consumption. Most
  356. of the time it is a better idea to use :attr:`data` which will give
  357. you that data as a string. The stream only returns the data once.
  358. Unlike :attr:`input_stream` this stream is properly guarded that you
  359. can't accidentally read past the length of the input. Werkzeug will
  360. internally always refer to this stream to read data which makes it
  361. possible to wrap this object with a stream that does filtering.
  362. .. versionchanged:: 0.9
  363. This stream is now always available but might be consumed by the
  364. form parser later on. Previously the stream was only set if no
  365. parsing happened.
  366. """
  367. _assert_not_shallow(self)
  368. return get_input_stream(self.environ)
  369. input_stream = environ_property('wsgi.input', """
  370. The WSGI input stream.
  371. In general it's a bad idea to use this one because you can easily read past
  372. the boundary. Use the :attr:`stream` instead.
  373. """)
  374. @cached_property
  375. def args(self):
  376. """The parsed URL parameters (the part in the URL after the question
  377. mark).
  378. By default an
  379. :class:`~werkzeug.datastructures.ImmutableMultiDict`
  380. is returned from this function. This can be changed by setting
  381. :attr:`parameter_storage_class` to a different type. This might
  382. be necessary if the order of the form data is important.
  383. """
  384. return url_decode(wsgi_get_bytes(self.environ.get('QUERY_STRING', '')),
  385. self.url_charset, errors=self.encoding_errors,
  386. cls=self.parameter_storage_class)
  387. @cached_property
  388. def data(self):
  389. """
  390. Contains the incoming request data as string in case it came with
  391. a mimetype Werkzeug does not handle.
  392. """
  393. if self.disable_data_descriptor:
  394. raise AttributeError('data descriptor is disabled')
  395. # XXX: this should eventually be deprecated.
  396. # We trigger form data parsing first which means that the descriptor
  397. # will not cache the data that would otherwise be .form or .files
  398. # data. This restores the behavior that was there in Werkzeug
  399. # before 0.9. New code should use :meth:`get_data` explicitly as
  400. # this will make behavior explicit.
  401. return self.get_data(parse_form_data=True)
  402. def get_data(self, cache=True, as_text=False, parse_form_data=False):
  403. """This reads the buffered incoming data from the client into one
  404. bytestring. By default this is cached but that behavior can be
  405. changed by setting `cache` to `False`.
  406. Usually it's a bad idea to call this method without checking the
  407. content length first as a client could send dozens of megabytes or more
  408. to cause memory problems on the server.
  409. Note that if the form data was already parsed this method will not
  410. return anything as form data parsing does not cache the data like
  411. this method does. To implicitly invoke form data parsing function
  412. set `parse_form_data` to `True`. When this is done the return value
  413. of this method will be an empty string if the form parser handles
  414. the data. This generally is not necessary as if the whole data is
  415. cached (which is the default) the form parser will used the cached
  416. data to parse the form data. Please be generally aware of checking
  417. the content length first in any case before calling this method
  418. to avoid exhausting server memory.
  419. If `as_text` is set to `True` the return value will be a decoded
  420. unicode string.
  421. .. versionadded:: 0.9
  422. """
  423. rv = getattr(self, '_cached_data', None)
  424. if rv is None:
  425. if parse_form_data:
  426. self._load_form_data()
  427. rv = self.stream.read()
  428. if cache:
  429. self._cached_data = rv
  430. if as_text:
  431. rv = rv.decode(self.charset, self.encoding_errors)
  432. return rv
  433. @cached_property
  434. def form(self):
  435. """The form parameters. By default an
  436. :class:`~werkzeug.datastructures.ImmutableMultiDict`
  437. is returned from this function. This can be changed by setting
  438. :attr:`parameter_storage_class` to a different type. This might
  439. be necessary if the order of the form data is important.
  440. Please keep in mind that file uploads will not end up here, but instead
  441. in the :attr:`files` attribute.
  442. .. versionchanged:: 0.9
  443. Previous to Werkzeug 0.9 this would only contain form data for POST
  444. and PUT requests.
  445. """
  446. self._load_form_data()
  447. return self.form
  448. @cached_property
  449. def values(self):
  450. """A :class:`werkzeug.datastructures.CombinedMultiDict` that combines
  451. :attr:`args` and :attr:`form`."""
  452. args = []
  453. for d in self.args, self.form:
  454. if not isinstance(d, MultiDict):
  455. d = MultiDict(d)
  456. args.append(d)
  457. return CombinedMultiDict(args)
  458. @cached_property
  459. def files(self):
  460. """:class:`~werkzeug.datastructures.MultiDict` object containing
  461. all uploaded files. Each key in :attr:`files` is the name from the
  462. ``<input type="file" name="">``. Each value in :attr:`files` is a
  463. Werkzeug :class:`~werkzeug.datastructures.FileStorage` object.
  464. It basically behaves like a standard file object you know from Python,
  465. with the difference that it also has a
  466. :meth:`~werkzeug.datastructures.FileStorage.save` function that can
  467. store the file on the filesystem.
  468. Note that :attr:`files` will only contain data if the request method was
  469. POST, PUT or PATCH and the ``<form>`` that posted to the request had
  470. ``enctype="multipart/form-data"``. It will be empty otherwise.
  471. See the :class:`~werkzeug.datastructures.MultiDict` /
  472. :class:`~werkzeug.datastructures.FileStorage` documentation for
  473. more details about the used data structure.
  474. """
  475. self._load_form_data()
  476. return self.files
  477. @cached_property
  478. def cookies(self):
  479. """A :class:`dict` with the contents of all cookies transmitted with
  480. the request."""
  481. return parse_cookie(self.environ, self.charset,
  482. self.encoding_errors,
  483. cls=self.dict_storage_class)
  484. @cached_property
  485. def headers(self):
  486. """The headers from the WSGI environ as immutable
  487. :class:`~werkzeug.datastructures.EnvironHeaders`.
  488. """
  489. return EnvironHeaders(self.environ)
  490. @cached_property
  491. def path(self):
  492. """Requested path as unicode. This works a bit like the regular path
  493. info in the WSGI environment but will always include a leading slash,
  494. even if the URL root is accessed.
  495. """
  496. raw_path = wsgi_decoding_dance(self.environ.get('PATH_INFO') or '',
  497. self.charset, self.encoding_errors)
  498. return '/' + raw_path.lstrip('/')
  499. @cached_property
  500. def full_path(self):
  501. """Requested path as unicode, including the query string."""
  502. return self.path + u'?' + to_unicode(self.query_string, self.url_charset)
  503. @cached_property
  504. def script_root(self):
  505. """The root path of the script without the trailing slash."""
  506. raw_path = wsgi_decoding_dance(self.environ.get('SCRIPT_NAME') or '',
  507. self.charset, self.encoding_errors)
  508. return raw_path.rstrip('/')
  509. @cached_property
  510. def url(self):
  511. """The reconstructed current URL as IRI.
  512. See also: :attr:`trusted_hosts`.
  513. """
  514. return get_current_url(self.environ,
  515. trusted_hosts=self.trusted_hosts)
  516. @cached_property
  517. def base_url(self):
  518. """Like :attr:`url` but without the querystring
  519. See also: :attr:`trusted_hosts`.
  520. """
  521. return get_current_url(self.environ, strip_querystring=True,
  522. trusted_hosts=self.trusted_hosts)
  523. @cached_property
  524. def url_root(self):
  525. """The full URL root (with hostname), this is the application
  526. root as IRI.
  527. See also: :attr:`trusted_hosts`.
  528. """
  529. return get_current_url(self.environ, True,
  530. trusted_hosts=self.trusted_hosts)
  531. @cached_property
  532. def host_url(self):
  533. """Just the host with scheme as IRI.
  534. See also: :attr:`trusted_hosts`.
  535. """
  536. return get_current_url(self.environ, host_only=True,
  537. trusted_hosts=self.trusted_hosts)
  538. @cached_property
  539. def host(self):
  540. """Just the host including the port if available.
  541. See also: :attr:`trusted_hosts`.
  542. """
  543. return get_host(self.environ, trusted_hosts=self.trusted_hosts)
  544. query_string = environ_property(
  545. 'QUERY_STRING', '', read_only=True,
  546. load_func=wsgi_get_bytes, doc='The URL parameters as raw bytestring.')
  547. method = environ_property(
  548. 'REQUEST_METHOD', 'GET', read_only=True,
  549. load_func=lambda x: x.upper(),
  550. doc="The request method. (For example ``'GET'`` or ``'POST'``).")
  551. @cached_property
  552. def access_route(self):
  553. """If a forwarded header exists this is a list of all ip addresses
  554. from the client ip to the last proxy server.
  555. """
  556. if 'HTTP_X_FORWARDED_FOR' in self.environ:
  557. addr = self.environ['HTTP_X_FORWARDED_FOR'].split(',')
  558. return self.list_storage_class([x.strip() for x in addr])
  559. elif 'REMOTE_ADDR' in self.environ:
  560. return self.list_storage_class([self.environ['REMOTE_ADDR']])
  561. return self.list_storage_class()
  562. @property
  563. def remote_addr(self):
  564. """The remote address of the client."""
  565. return self.environ.get('REMOTE_ADDR')
  566. remote_user = environ_property('REMOTE_USER', doc='''
  567. If the server supports user authentication, and the script is
  568. protected, this attribute contains the username the user has
  569. authenticated as.''')
  570. scheme = environ_property('wsgi.url_scheme', doc='''
  571. URL scheme (http or https).
  572. .. versionadded:: 0.7''')
  573. @property
  574. def is_xhr(self):
  575. """True if the request was triggered via a JavaScript XMLHttpRequest.
  576. This only works with libraries that support the ``X-Requested-With``
  577. header and set it to "XMLHttpRequest". Libraries that do that are
  578. prototype, jQuery and Mochikit and probably some more.
  579. .. deprecated:: 0.13
  580. ``X-Requested-With`` is not standard and is unreliable.
  581. """
  582. warn(DeprecationWarning(
  583. 'Request.is_xhr is deprecated. Given that the X-Requested-With '
  584. 'header is not a part of any spec, it is not reliable'
  585. ), stacklevel=2)
  586. return self.environ.get(
  587. 'HTTP_X_REQUESTED_WITH', ''
  588. ).lower() == 'xmlhttprequest'
  589. is_secure = property(lambda x: x.environ['wsgi.url_scheme'] == 'https',
  590. doc='`True` if the request is secure.')
  591. is_multithread = environ_property('wsgi.multithread', doc='''
  592. boolean that is `True` if the application is served by
  593. a multithreaded WSGI server.''')
  594. is_multiprocess = environ_property('wsgi.multiprocess', doc='''
  595. boolean that is `True` if the application is served by
  596. a WSGI server that spawns multiple processes.''')
  597. is_run_once = environ_property('wsgi.run_once', doc='''
  598. boolean that is `True` if the application will be executed only
  599. once in a process lifetime. This is the case for CGI for example,
  600. but it's not guaranteed that the execution only happens one time.''')
  601. class BaseResponse(object):
  602. """Base response class. The most important fact about a response object
  603. is that it's a regular WSGI application. It's initialized with a couple
  604. of response parameters (headers, body, status code etc.) and will start a
  605. valid WSGI response when called with the environ and start response
  606. callable.
  607. Because it's a WSGI application itself processing usually ends before the
  608. actual response is sent to the server. This helps debugging systems
  609. because they can catch all the exceptions before responses are started.
  610. Here a small example WSGI application that takes advantage of the
  611. response objects::
  612. from werkzeug.wrappers import BaseResponse as Response
  613. def index():
  614. return Response('Index page')
  615. def application(environ, start_response):
  616. path = environ.get('PATH_INFO') or '/'
  617. if path == '/':
  618. response = index()
  619. else:
  620. response = Response('Not Found', status=404)
  621. return response(environ, start_response)
  622. Like :class:`BaseRequest` which object is lacking a lot of functionality
  623. implemented in mixins. This gives you a better control about the actual
  624. API of your response objects, so you can create subclasses and add custom
  625. functionality. A full featured response object is available as
  626. :class:`Response` which implements a couple of useful mixins.
  627. To enforce a new type of already existing responses you can use the
  628. :meth:`force_type` method. This is useful if you're working with different
  629. subclasses of response objects and you want to post process them with a
  630. known interface.
  631. Per default the response object will assume all the text data is `utf-8`
  632. encoded. Please refer to `the unicode chapter <unicode.txt>`_ for more
  633. details about customizing the behavior.
  634. Response can be any kind of iterable or string. If it's a string it's
  635. considered being an iterable with one item which is the string passed.
  636. Headers can be a list of tuples or a
  637. :class:`~werkzeug.datastructures.Headers` object.
  638. Special note for `mimetype` and `content_type`: For most mime types
  639. `mimetype` and `content_type` work the same, the difference affects
  640. only 'text' mimetypes. If the mimetype passed with `mimetype` is a
  641. mimetype starting with `text/`, the charset parameter of the response
  642. object is appended to it. In contrast the `content_type` parameter is
  643. always added as header unmodified.
  644. .. versionchanged:: 0.5
  645. the `direct_passthrough` parameter was added.
  646. :param response: a string or response iterable.
  647. :param status: a string with a status or an integer with the status code.
  648. :param headers: a list of headers or a
  649. :class:`~werkzeug.datastructures.Headers` object.
  650. :param mimetype: the mimetype for the response. See notice above.
  651. :param content_type: the content type for the response. See notice above.
  652. :param direct_passthrough: if set to `True` :meth:`iter_encoded` is not
  653. called before iteration which makes it
  654. possible to pass special iterators through
  655. unchanged (see :func:`wrap_file` for more
  656. details.)
  657. """
  658. #: the charset of the response.
  659. charset = 'utf-8'
  660. #: the default status if none is provided.
  661. default_status = 200
  662. #: the default mimetype if none is provided.
  663. default_mimetype = 'text/plain'
  664. #: if set to `False` accessing properties on the response object will
  665. #: not try to consume the response iterator and convert it into a list.
  666. #:
  667. #: .. versionadded:: 0.6.2
  668. #:
  669. #: That attribute was previously called `implicit_seqence_conversion`.
  670. #: (Notice the typo). If you did use this feature, you have to adapt
  671. #: your code to the name change.
  672. implicit_sequence_conversion = True
  673. #: Should this response object correct the location header to be RFC
  674. #: conformant? This is true by default.
  675. #:
  676. #: .. versionadded:: 0.8
  677. autocorrect_location_header = True
  678. #: Should this response object automatically set the content-length
  679. #: header if possible? This is true by default.
  680. #:
  681. #: .. versionadded:: 0.8
  682. automatically_set_content_length = True
  683. #: Warn if a cookie header exceeds this size. The default, 4093, should be
  684. #: safely `supported by most browsers <cookie_>`_. A cookie larger than
  685. #: this size will still be sent, but it may be ignored or handled
  686. #: incorrectly by some browsers. Set to 0 to disable this check.
  687. #:
  688. #: .. versionadded:: 0.13
  689. #:
  690. #: .. _`cookie`: http://browsercookielimits.squawky.net/
  691. max_cookie_size = 4093
  692. def __init__(self, response=None, status=None, headers=None,
  693. mimetype=None, content_type=None, direct_passthrough=False):
  694. if isinstance(headers, Headers):
  695. self.headers = headers
  696. elif not headers:
  697. self.headers = Headers()
  698. else:
  699. self.headers = Headers(headers)
  700. if content_type is None:
  701. if mimetype is None and 'content-type' not in self.headers:
  702. mimetype = self.default_mimetype
  703. if mimetype is not None:
  704. mimetype = get_content_type(mimetype, self.charset)
  705. content_type = mimetype
  706. if content_type is not None:
  707. self.headers['Content-Type'] = content_type
  708. if status is None:
  709. status = self.default_status
  710. if isinstance(status, integer_types):
  711. self.status_code = status
  712. else:
  713. self.status = status
  714. self.direct_passthrough = direct_passthrough
  715. self._on_close = []
  716. # we set the response after the headers so that if a class changes
  717. # the charset attribute, the data is set in the correct charset.
  718. if response is None:
  719. self.response = []
  720. elif isinstance(response, (text_type, bytes, bytearray)):
  721. self.set_data(response)
  722. else:
  723. self.response = response
  724. def call_on_close(self, func):
  725. """Adds a function to the internal list of functions that should
  726. be called as part of closing down the response. Since 0.7 this
  727. function also returns the function that was passed so that this
  728. can be used as a decorator.
  729. .. versionadded:: 0.6
  730. """
  731. self._on_close.append(func)
  732. return func
  733. def __repr__(self):
  734. if self.is_sequence:
  735. body_info = '%d bytes' % sum(map(len, self.iter_encoded()))
  736. else:
  737. body_info = 'streamed' if self.is_streamed else 'likely-streamed'
  738. return '<%s %s [%s]>' % (
  739. self.__class__.__name__,
  740. body_info,
  741. self.status
  742. )
  743. @classmethod
  744. def force_type(cls, response, environ=None):
  745. """Enforce that the WSGI response is a response object of the current
  746. type. Werkzeug will use the :class:`BaseResponse` internally in many
  747. situations like the exceptions. If you call :meth:`get_response` on an
  748. exception you will get back a regular :class:`BaseResponse` object, even
  749. if you are using a custom subclass.
  750. This method can enforce a given response type, and it will also
  751. convert arbitrary WSGI callables into response objects if an environ
  752. is provided::
  753. # convert a Werkzeug response object into an instance of the
  754. # MyResponseClass subclass.
  755. response = MyResponseClass.force_type(response)
  756. # convert any WSGI application into a response object
  757. response = MyResponseClass.force_type(response, environ)
  758. This is especially useful if you want to post-process responses in
  759. the main dispatcher and use functionality provided by your subclass.
  760. Keep in mind that this will modify response objects in place if
  761. possible!
  762. :param response: a response object or wsgi application.
  763. :param environ: a WSGI environment object.
  764. :return: a response object.
  765. """
  766. if not isinstance(response, BaseResponse):
  767. if environ is None:
  768. raise TypeError('cannot convert WSGI application into '
  769. 'response objects without an environ')
  770. response = BaseResponse(*_run_wsgi_app(response, environ))
  771. response.__class__ = cls
  772. return response
  773. @classmethod
  774. def from_app(cls, app, environ, buffered=False):
  775. """Create a new response object from an application output. This
  776. works best if you pass it an application that returns a generator all
  777. the time. Sometimes applications may use the `write()` callable
  778. returned by the `start_response` function. This tries to resolve such
  779. edge cases automatically. But if you don't get the expected output
  780. you should set `buffered` to `True` which enforces buffering.
  781. :param app: the WSGI application to execute.
  782. :param environ: the WSGI environment to execute against.
  783. :param buffered: set to `True` to enforce buffering.
  784. :return: a response object.
  785. """
  786. return cls(*_run_wsgi_app(app, environ, buffered))
  787. def _get_status_code(self):
  788. return self._status_code
  789. def _set_status_code(self, code):
  790. self._status_code = code
  791. try:
  792. self._status = '%d %s' % (code, HTTP_STATUS_CODES[code].upper())
  793. except KeyError:
  794. self._status = '%d UNKNOWN' % code
  795. status_code = property(_get_status_code, _set_status_code,
  796. doc='The HTTP Status code as number')
  797. del _get_status_code, _set_status_code
  798. def _get_status(self):
  799. return self._status
  800. def _set_status(self, value):
  801. try:
  802. self._status = to_native(value)
  803. except AttributeError:
  804. raise TypeError('Invalid status argument')
  805. try:
  806. self._status_code = int(self._status.split(None, 1)[0])
  807. except ValueError:
  808. self._status_code = 0
  809. self._status = '0 %s' % self._status
  810. except IndexError:
  811. raise ValueError('Empty status argument')
  812. status = property(_get_status, _set_status, doc='The HTTP Status code')
  813. del _get_status, _set_status
  814. def get_data(self, as_text=False):
  815. """The string representation of the request body. Whenever you call
  816. this property the request iterable is encoded and flattened. This
  817. can lead to unwanted behavior if you stream big data.
  818. This behavior can be disabled by setting
  819. :attr:`implicit_sequence_conversion` to `False`.
  820. If `as_text` is set to `True` the return value will be a decoded
  821. unicode string.
  822. .. versionadded:: 0.9
  823. """
  824. self._ensure_sequence()
  825. rv = b''.join(self.iter_encoded())
  826. if as_text:
  827. rv = rv.decode(self.charset)
  828. return rv
  829. def set_data(self, value):
  830. """Sets a new string as response. The value set must either by a
  831. unicode or bytestring. If a unicode string is set it's encoded
  832. automatically to the charset of the response (utf-8 by default).
  833. .. versionadded:: 0.9
  834. """
  835. # if an unicode string is set, it's encoded directly so that we
  836. # can set the content length
  837. if isinstance(value, text_type):
  838. value = value.encode(self.charset)
  839. else:
  840. value = bytes(value)
  841. self.response = [value]
  842. if self.automatically_set_content_length:
  843. self.headers['Content-Length'] = str(len(value))
  844. data = property(get_data, set_data, doc='''
  845. A descriptor that calls :meth:`get_data` and :meth:`set_data`. This
  846. should not be used and will eventually get deprecated.
  847. ''')
  848. def calculate_content_length(self):
  849. """Returns the content length if available or `None` otherwise."""
  850. try:
  851. self._ensure_sequence()
  852. except RuntimeError:
  853. return None
  854. return sum(len(x) for x in self.iter_encoded())
  855. def _ensure_sequence(self, mutable=False):
  856. """This method can be called by methods that need a sequence. If
  857. `mutable` is true, it will also ensure that the response sequence
  858. is a standard Python list.
  859. .. versionadded:: 0.6
  860. """
  861. if self.is_sequence:
  862. # if we need a mutable object, we ensure it's a list.
  863. if mutable and not isinstance(self.response, list):
  864. self.response = list(self.response)
  865. return
  866. if self.direct_passthrough:
  867. raise RuntimeError('Attempted implicit sequence conversion '
  868. 'but the response object is in direct '
  869. 'passthrough mode.')
  870. if not self.implicit_sequence_conversion:
  871. raise RuntimeError('The response object required the iterable '
  872. 'to be a sequence, but the implicit '
  873. 'conversion was disabled. Call '
  874. 'make_sequence() yourself.')
  875. self.make_sequence()
  876. def make_sequence(self):
  877. """Converts the response iterator in a list. By default this happens
  878. automatically if required. If `implicit_sequence_conversion` is
  879. disabled, this method is not automatically called and some properties
  880. might raise exceptions. This also encodes all the items.
  881. .. versionadded:: 0.6
  882. """
  883. if not self.is_sequence:
  884. # if we consume an iterable we have to ensure that the close
  885. # method of the iterable is called if available when we tear
  886. # down the response
  887. close = getattr(self.response, 'close', None)
  888. self.response = list(self.iter_encoded())
  889. if close is not None:
  890. self.call_on_close(close)
  891. def iter_encoded(self):
  892. """Iter the response encoded with the encoding of the response.
  893. If the response object is invoked as WSGI application the return
  894. value of this method is used as application iterator unless
  895. :attr:`direct_passthrough` was activated.
  896. """
  897. if __debug__:
  898. _warn_if_string(self.response)
  899. # Encode in a separate function so that self.response is fetched
  900. # early. This allows us to wrap the response with the return
  901. # value from get_app_iter or iter_encoded.
  902. return _iter_encoded(self.response, self.charset)
  903. def set_cookie(self, key, value='', max_age=None, expires=None,
  904. path='/', domain=None, secure=False, httponly=False,
  905. samesite=None):
  906. """Sets a cookie. The parameters are the same as in the cookie `Morsel`
  907. object in the Python standard library but it accepts unicode data, too.
  908. A warning is raised if the size of the cookie header exceeds
  909. :attr:`max_cookie_size`, but the header will still be set.
  910. :param key: the key (name) of the cookie to be set.
  911. :param value: the value of the cookie.
  912. :param max_age: should be a number of seconds, or `None` (default) if
  913. the cookie should last only as long as the client's
  914. browser session.
  915. :param expires: should be a `datetime` object or UNIX timestamp.
  916. :param path: limits the cookie to a given path, per default it will
  917. span the whole domain.
  918. :param domain: if you want to set a cross-domain cookie. For example,
  919. ``domain=".example.com"`` will set a cookie that is
  920. readable by the domain ``www.example.com``,
  921. ``foo.example.com`` etc. Otherwise, a cookie will only
  922. be readable by the domain that set it.
  923. :param secure: If `True`, the cookie will only be available via HTTPS
  924. :param httponly: disallow JavaScript to access the cookie. This is an
  925. extension to the cookie standard and probably not
  926. supported by all browsers.
  927. :param samesite: Limits the scope of the cookie such that it will only
  928. be attached to requests if those requests are
  929. "same-site".
  930. """
  931. self.headers.add('Set-Cookie', dump_cookie(
  932. key,
  933. value=value,
  934. max_age=max_age,
  935. expires=expires,
  936. path=path,
  937. domain=domain,
  938. secure=secure,
  939. httponly=httponly,
  940. charset=self.charset,
  941. max_size=self.max_cookie_size,
  942. samesite=samesite
  943. ))
  944. def delete_cookie(self, key, path='/', domain=None):
  945. """Delete a cookie. Fails silently if key doesn't exist.
  946. :param key: the key (name) of the cookie to be deleted.
  947. :param path: if the cookie that should be deleted was limited to a
  948. path, the path has to be defined here.
  949. :param domain: if the cookie that should be deleted was limited to a
  950. domain, that domain has to be defined here.
  951. """
  952. self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
  953. @property
  954. def is_streamed(self):
  955. """If the response is streamed (the response is not an iterable with
  956. a length information) this property is `True`. In this case streamed
  957. means that there is no information about the number of iterations.
  958. This is usually `True` if a generator is passed to the response object.
  959. This is useful for checking before applying some sort of post
  960. filtering that should not take place for streamed responses.
  961. """
  962. try:
  963. len(self.response)
  964. except (TypeError, AttributeError):
  965. return True
  966. return False
  967. @property
  968. def is_sequence(self):
  969. """If the iterator is buffered, this property will be `True`. A
  970. response object will consider an iterator to be buffered if the
  971. response attribute is a list or tuple.
  972. .. versionadded:: 0.6
  973. """
  974. return isinstance(self.response, (tuple, list))
  975. def close(self):
  976. """Close the wrapped response if possible. You can also use the object
  977. in a with statement which will automatically close it.
  978. .. versionadded:: 0.9
  979. Can now be used in a with statement.
  980. """
  981. if hasattr(self.response, 'close'):
  982. self.response.close()
  983. for func in self._on_close:
  984. func()
  985. def __enter__(self):
  986. return self
  987. def __exit__(self, exc_type, exc_value, tb):
  988. self.close()
  989. def freeze(self):
  990. """Call this method if you want to make your response object ready for
  991. being pickled. This buffers the generator if there is one. It will
  992. also set the `Content-Length` header to the length of the body.
  993. .. versionchanged:: 0.6
  994. The `Content-Length` header is now set.
  995. """
  996. # we explicitly set the length to a list of the *encoded* response
  997. # iterator. Even if the implicit sequence conversion is disabled.
  998. self.response = list(self.iter_encoded())
  999. self.headers['Content-Length'] = str(sum(map(len, self.response)))
  1000. def get_wsgi_headers(self, environ):
  1001. """This is automatically called right before the response is started
  1002. and returns headers modified for the given environment. It returns a
  1003. copy of the headers from the response with some modifications applied
  1004. if necessary.
  1005. For example the location header (if present) is joined with the root
  1006. URL of the environment. Also the content length is automatically set
  1007. to zero here for certain status codes.
  1008. .. versionchanged:: 0.6
  1009. Previously that function was called `fix_headers` and modified
  1010. the response object in place. Also since 0.6, IRIs in location
  1011. and content-location headers are handled properly.
  1012. Also starting with 0.6, Werkzeug will attempt to set the content
  1013. length if it is able to figure it out on its own. This is the
  1014. case if all the strings in the response iterable are already
  1015. encoded and the iterable is buffered.
  1016. :param environ: the WSGI environment of the request.
  1017. :return: returns a new :class:`~werkzeug.datastructures.Headers`
  1018. object.
  1019. """
  1020. headers = Headers(self.headers)
  1021. location = None
  1022. content_location = None
  1023. content_length = None
  1024. status = self.status_code
  1025. # iterate over the headers to find all values in one go. Because
  1026. # get_wsgi_headers is used each response that gives us a tiny
  1027. # speedup.
  1028. for key, value in headers:
  1029. ikey = key.lower()
  1030. if ikey == u'location':
  1031. location = value
  1032. elif ikey == u'content-location':
  1033. content_location = value
  1034. elif ikey == u'content-length':
  1035. content_length = value
  1036. # make sure the location header is an absolute URL
  1037. if location is not None:
  1038. old_location = location
  1039. if isinstance(location, text_type):
  1040. # Safe conversion is necessary here as we might redirect
  1041. # to a broken URI scheme (for instance itms-services).
  1042. location = iri_to_uri(location, safe_conversion=True)
  1043. if self.autocorrect_location_header:
  1044. current_url = get_current_url(environ, root_only=True)
  1045. if isinstance(current_url, text_type):
  1046. current_url = iri_to_uri(current_url)
  1047. location = url_join(current_url, location)
  1048. if location != old_location:
  1049. headers['Location'] = location
  1050. # make sure the content location is a URL
  1051. if content_location is not None and \
  1052. isinstance(content_location, text_type):
  1053. headers['Content-Location'] = iri_to_uri(content_location)
  1054. if status in (304, 412):
  1055. remove_entity_headers(headers)
  1056. # if we can determine the content length automatically, we
  1057. # should try to do that. But only if this does not involve
  1058. # flattening the iterator or encoding of unicode strings in
  1059. # the response. We however should not do that if we have a 304
  1060. # response.
  1061. if self.automatically_set_content_length and \
  1062. self.is_sequence and content_length is None and \
  1063. status not in (204, 304) and \
  1064. not (100 <= status < 200):
  1065. try:
  1066. content_length = sum(len(to_bytes(x, 'ascii'))
  1067. for x in self.response)
  1068. except UnicodeError:
  1069. # aha, something non-bytestringy in there, too bad, we
  1070. # can't safely figure out the length of the response.
  1071. pass
  1072. else:
  1073. headers['Content-Length'] = str(content_length)
  1074. return headers
  1075. def get_app_iter(self, environ):
  1076. """Returns the application iterator for the given environ. Depending
  1077. on the request method and the current status code the return value
  1078. might be an empty response rather than the one from the response.
  1079. If the request method is `HEAD` or the status code is in a range
  1080. where the HTTP specification requires an empty response, an empty
  1081. iterable is returned.
  1082. .. versionadded:: 0.6
  1083. :param environ: the WSGI environment of the request.
  1084. :return: a response iterable.
  1085. """
  1086. status = self.status_code
  1087. if environ['REQUEST_METHOD'] == 'HEAD' or \
  1088. 100 <= status < 200 or status in (204, 304, 412):
  1089. iterable = ()
  1090. elif self.direct_passthrough:
  1091. if __debug__:
  1092. _warn_if_string(self.response)
  1093. return self.response
  1094. else:
  1095. iterable = self.iter_encoded()
  1096. return ClosingIterator(iterable, self.close)
  1097. def get_wsgi_response(self, environ):
  1098. """Returns the final WSGI response as tuple. The first item in
  1099. the tuple is the application iterator, the second the status and
  1100. the third the list of headers. The response returned is created
  1101. specially for the given environment. For example if the request
  1102. method in the WSGI environment is ``'HEAD'`` the response will
  1103. be empty and only the headers and status code will be present.
  1104. .. versionadded:: 0.6
  1105. :param environ: the WSGI environment of the request.
  1106. :return: an ``(app_iter, status, headers)`` tuple.
  1107. """
  1108. headers = self.get_wsgi_headers(environ)
  1109. app_iter = self.get_app_iter(environ)
  1110. return app_iter, self.status, headers.to_wsgi_list()
  1111. def __call__(self, environ, start_response):
  1112. """Process this response as WSGI application.
  1113. :param environ: the WSGI environment.
  1114. :param start_response: the response callable provided by the WSGI
  1115. server.
  1116. :return: an application iterator
  1117. """
  1118. app_iter, status, headers = self.get_wsgi_response(environ)
  1119. start_response(status, headers)
  1120. return app_iter
  1121. class AcceptMixin(object):
  1122. """A mixin for classes with an :attr:`~BaseResponse.environ` attribute
  1123. to get all the HTTP accept headers as
  1124. :class:`~werkzeug.datastructures.Accept` objects (or subclasses
  1125. thereof).
  1126. """
  1127. @cached_property
  1128. def accept_mimetypes(self):
  1129. """List of mimetypes this client supports as
  1130. :class:`~werkzeug.datastructures.MIMEAccept` object.
  1131. """
  1132. return parse_accept_header(self.environ.get('HTTP_ACCEPT'), MIMEAccept)
  1133. @cached_property
  1134. def accept_charsets(self):
  1135. """List of charsets this client supports as
  1136. :class:`~werkzeug.datastructures.CharsetAccept` object.
  1137. """
  1138. return parse_accept_header(self.environ.get('HTTP_ACCEPT_CHARSET'),
  1139. CharsetAccept)
  1140. @cached_property
  1141. def accept_encodings(self):
  1142. """List of encodings this client accepts. Encodings in a HTTP term
  1143. are compression encodings such as gzip. For charsets have a look at
  1144. :attr:`accept_charset`.
  1145. """
  1146. return parse_accept_header(self.environ.get('HTTP_ACCEPT_ENCODING'))
  1147. @cached_property
  1148. def accept_languages(self):
  1149. """List of languages this client accepts as
  1150. :class:`~werkzeug.datastructures.LanguageAccept` object.
  1151. .. versionchanged 0.5
  1152. In previous versions this was a regular
  1153. :class:`~werkzeug.datastructures.Accept` object.
  1154. """
  1155. return parse_accept_header(self.environ.get('HTTP_ACCEPT_LANGUAGE'),
  1156. LanguageAccept)
  1157. class ETagRequestMixin(object):
  1158. """Add entity tag and cache descriptors to a request object or object with
  1159. a WSGI environment available as :attr:`~BaseRequest.environ`. This not
  1160. only provides access to etags but also to the cache control header.
  1161. """
  1162. @cached_property
  1163. def cache_control(self):
  1164. """A :class:`~werkzeug.datastructures.RequestCacheControl` object
  1165. for the incoming cache control headers.
  1166. """
  1167. cache_control = self.environ.get('HTTP_CACHE_CONTROL')
  1168. return parse_cache_control_header(cache_control, None,
  1169. RequestCacheControl)
  1170. @cached_property
  1171. def if_match(self):
  1172. """An object containing all the etags in the `If-Match` header.
  1173. :rtype: :class:`~werkzeug.datastructures.ETags`
  1174. """
  1175. return parse_etags(self.environ.get('HTTP_IF_MATCH'))
  1176. @cached_property
  1177. def if_none_match(self):
  1178. """An object containing all the etags in the `If-None-Match` header.
  1179. :rtype: :class:`~werkzeug.datastructures.ETags`
  1180. """
  1181. return parse_etags(self.environ.get('HTTP_IF_NONE_MATCH'))
  1182. @cached_property
  1183. def if_modified_since(self):
  1184. """The parsed `If-Modified-Since` header as datetime object."""
  1185. return parse_date(self.environ.get('HTTP_IF_MODIFIED_SINCE'))
  1186. @cached_property
  1187. def if_unmodified_since(self):
  1188. """The parsed `If-Unmodified-Since` header as datetime object."""
  1189. return parse_date(self.environ.get('HTTP_IF_UNMODIFIED_SINCE'))
  1190. @cached_property
  1191. def if_range(self):
  1192. """The parsed `If-Range` header.
  1193. .. versionadded:: 0.7
  1194. :rtype: :class:`~werkzeug.datastructures.IfRange`
  1195. """
  1196. return parse_if_range_header(self.environ.get('HTTP_IF_RANGE'))
  1197. @cached_property
  1198. def range(self):
  1199. """The parsed `Range` header.
  1200. .. versionadded:: 0.7
  1201. :rtype: :class:`~werkzeug.datastructures.Range`
  1202. """
  1203. return parse_range_header(self.environ.get('HTTP_RANGE'))
  1204. class UserAgentMixin(object):
  1205. """Adds a `user_agent` attribute to the request object which contains the
  1206. parsed user agent of the browser that triggered the request as a
  1207. :class:`~werkzeug.useragents.UserAgent` object.
  1208. """
  1209. @cached_property
  1210. def user_agent(self):
  1211. """The current user agent."""
  1212. from werkzeug.useragents import UserAgent
  1213. return UserAgent(self.environ)
  1214. class AuthorizationMixin(object):
  1215. """Adds an :attr:`authorization` property that represents the parsed
  1216. value of the `Authorization` header as
  1217. :class:`~werkzeug.datastructures.Authorization` object.
  1218. """
  1219. @cached_property
  1220. def authorization(self):
  1221. """The `Authorization` object in parsed form."""
  1222. header = self.environ.get('HTTP_AUTHORIZATION')
  1223. return parse_authorization_header(header)
  1224. class StreamOnlyMixin(object):
  1225. """If mixed in before the request object this will change the bahavior
  1226. of it to disable handling of form parsing. This disables the
  1227. :attr:`files`, :attr:`form` attributes and will just provide a
  1228. :attr:`stream` attribute that however is always available.
  1229. .. versionadded:: 0.9
  1230. """
  1231. disable_data_descriptor = True
  1232. want_form_data_parsed = False
  1233. class ETagResponseMixin(object):
  1234. """Adds extra functionality to a response object for etag and cache
  1235. handling. This mixin requires an object with at least a `headers`
  1236. object that implements a dict like interface similar to
  1237. :class:`~werkzeug.datastructures.Headers`.
  1238. If you want the :meth:`freeze` method to automatically add an etag, you
  1239. have to mixin this method before the response base class. The default
  1240. response class does not do that.
  1241. """
  1242. @property
  1243. def cache_control(self):
  1244. """The Cache-Control general-header field is used to specify
  1245. directives that MUST be obeyed by all caching mechanisms along the
  1246. request/response chain.
  1247. """
  1248. def on_update(cache_control):
  1249. if not cache_control and 'cache-control' in self.headers:
  1250. del self.headers['cache-control']
  1251. elif cache_control:
  1252. self.headers['Cache-Control'] = cache_control.to_header()
  1253. return parse_cache_control_header(self.headers.get('cache-control'),
  1254. on_update,
  1255. ResponseCacheControl)
  1256. def _wrap_response(self, start, length):
  1257. """Wrap existing Response in case of Range Request context."""
  1258. if self.status_code == 206:
  1259. self.response = _RangeWrapper(self.response, start, length)
  1260. def _is_range_request_processable(self, environ):
  1261. """Return ``True`` if `Range` header is present and if underlying
  1262. resource is considered unchanged when compared with `If-Range` header.
  1263. """
  1264. return (
  1265. 'HTTP_IF_RANGE' not in environ
  1266. or not is_resource_modified(
  1267. environ, self.headers.get('etag'), None,
  1268. self.headers.get('last-modified'), ignore_if_range=False
  1269. )
  1270. ) and 'HTTP_RANGE' in environ
  1271. def _process_range_request(self, environ, complete_length=None, accept_ranges=None):
  1272. """Handle Range Request related headers (RFC7233). If `Accept-Ranges`
  1273. header is valid, and Range Request is processable, we set the headers
  1274. as described by the RFC, and wrap the underlying response in a
  1275. RangeWrapper.
  1276. Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise.
  1277. :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
  1278. if `Range` header could not be parsed or satisfied.
  1279. """
  1280. from werkzeug.exceptions import RequestedRangeNotSatisfiable
  1281. if accept_ranges is None:
  1282. return False
  1283. self.headers['Accept-Ranges'] = accept_ranges
  1284. if not self._is_range_request_processable(environ) or complete_length is None:
  1285. return False
  1286. parsed_range = parse_range_header(environ.get('HTTP_RANGE'))
  1287. if parsed_range is None:
  1288. raise RequestedRangeNotSatisfiable(complete_length)
  1289. range_tuple = parsed_range.range_for_length(complete_length)
  1290. content_range_header = parsed_range.to_content_range_header(complete_length)
  1291. if range_tuple is None or content_range_header is None:
  1292. raise RequestedRangeNotSatisfiable(complete_length)
  1293. content_length = range_tuple[1] - range_tuple[0]
  1294. # Be sure not to send 206 response
  1295. # if requested range is the full content.
  1296. if content_length != complete_length:
  1297. self.headers['Content-Length'] = content_length
  1298. self.content_range = content_range_header
  1299. self.status_code = 206
  1300. self._wrap_response(range_tuple[0], content_length)
  1301. return True
  1302. return False
  1303. def make_conditional(self, request_or_environ, accept_ranges=False,
  1304. complete_length=None):
  1305. """Make the response conditional to the request. This method works
  1306. best if an etag was defined for the response already. The `add_etag`
  1307. method can be used to do that. If called without etag just the date
  1308. header is set.
  1309. This does nothing if the request method in the request or environ is
  1310. anything but GET or HEAD.
  1311. For optimal performance when handling range requests, it's recommended
  1312. that your response data object implements `seekable`, `seek` and `tell`
  1313. methods as described by :py:class:`io.IOBase`. Objects returned by
  1314. :meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods.
  1315. It does not remove the body of the response because that's something
  1316. the :meth:`__call__` function does for us automatically.
  1317. Returns self so that you can do ``return resp.make_conditional(req)``
  1318. but modifies the object in-place.
  1319. :param request_or_environ: a request object or WSGI environment to be
  1320. used to make the response conditional
  1321. against.
  1322. :param accept_ranges: This parameter dictates the value of
  1323. `Accept-Ranges` header. If ``False`` (default),
  1324. the header is not set. If ``True``, it will be set
  1325. to ``"bytes"``. If ``None``, it will be set to
  1326. ``"none"``. If it's a string, it will use this
  1327. value.
  1328. :param complete_length: Will be used only in valid Range Requests.
  1329. It will set `Content-Range` complete length
  1330. value and compute `Content-Length` real value.
  1331. This parameter is mandatory for successful
  1332. Range Requests completion.
  1333. :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
  1334. if `Range` header could not be parsed or satisfied.
  1335. """
  1336. environ = _get_environ(request_or_environ)
  1337. if environ['REQUEST_METHOD'] in ('GET', 'HEAD'):
  1338. # if the date is not in the headers, add it now. We however
  1339. # will not override an already existing header. Unfortunately
  1340. # this header will be overriden by many WSGI servers including
  1341. # wsgiref.
  1342. if 'date' not in self.headers:
  1343. self.headers['Date'] = http_date()
  1344. accept_ranges = _clean_accept_ranges(accept_ranges)
  1345. is206 = self._process_range_request(environ, complete_length, accept_ranges)
  1346. if not is206 and not is_resource_modified(
  1347. environ, self.headers.get('etag'), None,
  1348. self.headers.get('last-modified')
  1349. ):
  1350. if parse_etags(environ.get('HTTP_IF_MATCH')):
  1351. self.status_code = 412
  1352. else:
  1353. self.status_code = 304
  1354. if self.automatically_set_content_length and 'content-length' not in self.headers:
  1355. length = self.calculate_content_length()
  1356. if length is not None:
  1357. self.headers['Content-Length'] = length
  1358. return self
  1359. def add_etag(self, overwrite=False, weak=False):
  1360. """Add an etag for the current response if there is none yet."""
  1361. if overwrite or 'etag' not in self.headers:
  1362. self.set_etag(generate_etag(self.get_data()), weak)
  1363. def set_etag(self, etag, weak=False):
  1364. """Set the etag, and override the old one if there was one."""
  1365. self.headers['ETag'] = quote_etag(etag, weak)
  1366. def get_etag(self):
  1367. """Return a tuple in the form ``(etag, is_weak)``. If there is no
  1368. ETag the return value is ``(None, None)``.
  1369. """
  1370. return unquote_etag(self.headers.get('ETag'))
  1371. def freeze(self, no_etag=False):
  1372. """Call this method if you want to make your response object ready for
  1373. pickeling. This buffers the generator if there is one. This also
  1374. sets the etag unless `no_etag` is set to `True`.
  1375. """
  1376. if not no_etag:
  1377. self.add_etag()
  1378. super(ETagResponseMixin, self).freeze()
  1379. accept_ranges = header_property('Accept-Ranges', doc='''
  1380. The `Accept-Ranges` header. Even though the name would indicate
  1381. that multiple values are supported, it must be one string token only.
  1382. The values ``'bytes'`` and ``'none'`` are common.
  1383. .. versionadded:: 0.7''')
  1384. def _get_content_range(self):
  1385. def on_update(rng):
  1386. if not rng:
  1387. del self.headers['content-range']
  1388. else:
  1389. self.headers['Content-Range'] = rng.to_header()
  1390. rv = parse_content_range_header(self.headers.get('content-range'),
  1391. on_update)
  1392. # always provide a content range object to make the descriptor
  1393. # more user friendly. It provides an unset() method that can be
  1394. # used to remove the header quickly.
  1395. if rv is None:
  1396. rv = ContentRange(None, None, None, on_update=on_update)
  1397. return rv
  1398. def _set_content_range(self, value):
  1399. if not value:
  1400. del self.headers['content-range']
  1401. elif isinstance(value, string_types):
  1402. self.headers['Content-Range'] = value
  1403. else:
  1404. self.headers['Content-Range'] = value.to_header()
  1405. content_range = property(_get_content_range, _set_content_range, doc='''
  1406. The `Content-Range` header as
  1407. :class:`~werkzeug.datastructures.ContentRange` object. Even if the
  1408. header is not set it wil provide such an object for easier
  1409. manipulation.
  1410. .. versionadded:: 0.7''')
  1411. del _get_content_range, _set_content_range
  1412. class ResponseStream(object):
  1413. """A file descriptor like object used by the :class:`ResponseStreamMixin` to
  1414. represent the body of the stream. It directly pushes into the response
  1415. iterable of the response object.
  1416. """
  1417. mode = 'wb+'
  1418. def __init__(self, response):
  1419. self.response = response
  1420. self.closed = False
  1421. def write(self, value):
  1422. if self.closed:
  1423. raise ValueError('I/O operation on closed file')
  1424. self.response._ensure_sequence(mutable=True)
  1425. self.response.response.append(value)
  1426. self.response.headers.pop('Content-Length', None)
  1427. return len(value)
  1428. def writelines(self, seq):
  1429. for item in seq:
  1430. self.write(item)
  1431. def close(self):
  1432. self.closed = True
  1433. def flush(self):
  1434. if self.closed:
  1435. raise ValueError('I/O operation on closed file')
  1436. def isatty(self):
  1437. if self.closed:
  1438. raise ValueError('I/O operation on closed file')
  1439. return False
  1440. def tell(self):
  1441. self.response._ensure_sequence()
  1442. return sum(map(len, self.response.response))
  1443. @property
  1444. def encoding(self):
  1445. return self.response.charset
  1446. class ResponseStreamMixin(object):
  1447. """Mixin for :class:`BaseRequest` subclasses. Classes that inherit from
  1448. this mixin will automatically get a :attr:`stream` property that provides
  1449. a write-only interface to the response iterable.
  1450. """
  1451. @cached_property
  1452. def stream(self):
  1453. """The response iterable as write-only stream."""
  1454. return ResponseStream(self)
  1455. class CommonRequestDescriptorsMixin(object):
  1456. """A mixin for :class:`BaseRequest` subclasses. Request objects that
  1457. mix this class in will automatically get descriptors for a couple of
  1458. HTTP headers with automatic type conversion.
  1459. .. versionadded:: 0.5
  1460. """
  1461. content_type = environ_property('CONTENT_TYPE', doc='''
  1462. The Content-Type entity-header field indicates the media type of
  1463. the entity-body sent to the recipient or, in the case of the HEAD
  1464. method, the media type that would have been sent had the request
  1465. been a GET.''')
  1466. @cached_property
  1467. def content_length(self):
  1468. """The Content-Length entity-header field indicates the size of the
  1469. entity-body in bytes or, in the case of the HEAD method, the size of
  1470. the entity-body that would have been sent had the request been a
  1471. GET.
  1472. """
  1473. return get_content_length(self.environ)
  1474. content_encoding = environ_property('HTTP_CONTENT_ENCODING', doc='''
  1475. The Content-Encoding entity-header field is used as a modifier to the
  1476. media-type. When present, its value indicates what additional content
  1477. codings have been applied to the entity-body, and thus what decoding
  1478. mechanisms must be applied in order to obtain the media-type
  1479. referenced by the Content-Type header field.
  1480. .. versionadded:: 0.9''')
  1481. content_md5 = environ_property('HTTP_CONTENT_MD5', doc='''
  1482. The Content-MD5 entity-header field, as defined in RFC 1864, is an
  1483. MD5 digest of the entity-body for the purpose of providing an
  1484. end-to-end message integrity check (MIC) of the entity-body. (Note:
  1485. a MIC is good for detecting accidental modification of the
  1486. entity-body in transit, but is not proof against malicious attacks.)
  1487. .. versionadded:: 0.9''')
  1488. referrer = environ_property('HTTP_REFERER', doc='''
  1489. The Referer[sic] request-header field allows the client to specify,
  1490. for the server's benefit, the address (URI) of the resource from which
  1491. the Request-URI was obtained (the "referrer", although the header
  1492. field is misspelled).''')
  1493. date = environ_property('HTTP_DATE', None, parse_date, doc='''
  1494. The Date general-header field represents the date and time at which
  1495. the message was originated, having the same semantics as orig-date
  1496. in RFC 822.''')
  1497. max_forwards = environ_property('HTTP_MAX_FORWARDS', None, int, doc='''
  1498. The Max-Forwards request-header field provides a mechanism with the
  1499. TRACE and OPTIONS methods to limit the number of proxies or gateways
  1500. that can forward the request to the next inbound server.''')
  1501. def _parse_content_type(self):
  1502. if not hasattr(self, '_parsed_content_type'):
  1503. self._parsed_content_type = \
  1504. parse_options_header(self.environ.get('CONTENT_TYPE', ''))
  1505. @property
  1506. def mimetype(self):
  1507. """Like :attr:`content_type`, but without parameters (eg, without
  1508. charset, type etc.) and always lowercase. For example if the content
  1509. type is ``text/HTML; charset=utf-8`` the mimetype would be
  1510. ``'text/html'``.
  1511. """
  1512. self._parse_content_type()
  1513. return self._parsed_content_type[0].lower()
  1514. @property
  1515. def mimetype_params(self):
  1516. """The mimetype parameters as dict. For example if the content
  1517. type is ``text/html; charset=utf-8`` the params would be
  1518. ``{'charset': 'utf-8'}``.
  1519. """
  1520. self._parse_content_type()
  1521. return self._parsed_content_type[1]
  1522. @cached_property
  1523. def pragma(self):
  1524. """The Pragma general-header field is used to include
  1525. implementation-specific directives that might apply to any recipient
  1526. along the request/response chain. All pragma directives specify
  1527. optional behavior from the viewpoint of the protocol; however, some
  1528. systems MAY require that behavior be consistent with the directives.
  1529. """
  1530. return parse_set_header(self.environ.get('HTTP_PRAGMA', ''))
  1531. class CommonResponseDescriptorsMixin(object):
  1532. """A mixin for :class:`BaseResponse` subclasses. Response objects that
  1533. mix this class in will automatically get descriptors for a couple of
  1534. HTTP headers with automatic type conversion.
  1535. """
  1536. def _get_mimetype(self):
  1537. ct = self.headers.get('content-type')
  1538. if ct:
  1539. return ct.split(';')[0].strip()
  1540. def _set_mimetype(self, value):
  1541. self.headers['Content-Type'] = get_content_type(value, self.charset)
  1542. def _get_mimetype_params(self):
  1543. def on_update(d):
  1544. self.headers['Content-Type'] = \
  1545. dump_options_header(self.mimetype, d)
  1546. d = parse_options_header(self.headers.get('content-type', ''))[1]
  1547. return CallbackDict(d, on_update)
  1548. mimetype = property(_get_mimetype, _set_mimetype, doc='''
  1549. The mimetype (content type without charset etc.)''')
  1550. mimetype_params = property(_get_mimetype_params, doc='''
  1551. The mimetype parameters as dict. For example if the content
  1552. type is ``text/html; charset=utf-8`` the params would be
  1553. ``{'charset': 'utf-8'}``.
  1554. .. versionadded:: 0.5
  1555. ''')
  1556. location = header_property('Location', doc='''
  1557. The Location response-header field is used to redirect the recipient
  1558. to a location other than the Request-URI for completion of the request
  1559. or identification of a new resource.''')
  1560. age = header_property('Age', None, parse_age, dump_age, doc='''
  1561. The Age response-header field conveys the sender's estimate of the
  1562. amount of time since the response (or its revalidation) was
  1563. generated at the origin server.
  1564. Age values are non-negative decimal integers, representing time in
  1565. seconds.''')
  1566. content_type = header_property('Content-Type', doc='''
  1567. The Content-Type entity-header field indicates the media type of the
  1568. entity-body sent to the recipient or, in the case of the HEAD method,
  1569. the media type that would have been sent had the request been a GET.
  1570. ''')
  1571. content_length = header_property('Content-Length', None, int, str, doc='''
  1572. The Content-Length entity-header field indicates the size of the
  1573. entity-body, in decimal number of OCTETs, sent to the recipient or,
  1574. in the case of the HEAD method, the size of the entity-body that would
  1575. have been sent had the request been a GET.''')
  1576. content_location = header_property('Content-Location', doc='''
  1577. The Content-Location entity-header field MAY be used to supply the
  1578. resource location for the entity enclosed in the message when that
  1579. entity is accessible from a location separate from the requested
  1580. resource's URI.''')
  1581. content_encoding = header_property('Content-Encoding', doc='''
  1582. The Content-Encoding entity-header field is used as a modifier to the
  1583. media-type. When present, its value indicates what additional content
  1584. codings have been applied to the entity-body, and thus what decoding
  1585. mechanisms must be applied in order to obtain the media-type
  1586. referenced by the Content-Type header field.''')
  1587. content_md5 = header_property('Content-MD5', doc='''
  1588. The Content-MD5 entity-header field, as defined in RFC 1864, is an
  1589. MD5 digest of the entity-body for the purpose of providing an
  1590. end-to-end message integrity check (MIC) of the entity-body. (Note:
  1591. a MIC is good for detecting accidental modification of the
  1592. entity-body in transit, but is not proof against malicious attacks.)
  1593. ''')
  1594. date = header_property('Date', None, parse_date, http_date, doc='''
  1595. The Date general-header field represents the date and time at which
  1596. the message was originated, having the same semantics as orig-date
  1597. in RFC 822.''')
  1598. expires = header_property('Expires', None, parse_date, http_date, doc='''
  1599. The Expires entity-header field gives the date/time after which the
  1600. response is considered stale. A stale cache entry may not normally be
  1601. returned by a cache.''')
  1602. last_modified = header_property('Last-Modified', None, parse_date,
  1603. http_date, doc='''
  1604. The Last-Modified entity-header field indicates the date and time at
  1605. which the origin server believes the variant was last modified.''')
  1606. def _get_retry_after(self):
  1607. value = self.headers.get('retry-after')
  1608. if value is None:
  1609. return
  1610. elif value.isdigit():
  1611. return datetime.utcnow() + timedelta(seconds=int(value))
  1612. return parse_date(value)
  1613. def _set_retry_after(self, value):
  1614. if value is None:
  1615. if 'retry-after' in self.headers:
  1616. del self.headers['retry-after']
  1617. return
  1618. elif isinstance(value, datetime):
  1619. value = http_date(value)
  1620. else:
  1621. value = str(value)
  1622. self.headers['Retry-After'] = value
  1623. retry_after = property(_get_retry_after, _set_retry_after, doc='''
  1624. The Retry-After response-header field can be used with a 503 (Service
  1625. Unavailable) response to indicate how long the service is expected
  1626. to be unavailable to the requesting client.
  1627. Time in seconds until expiration or date.''')
  1628. def _set_property(name, doc=None):
  1629. def fget(self):
  1630. def on_update(header_set):
  1631. if not header_set and name in self.headers:
  1632. del self.headers[name]
  1633. elif header_set:
  1634. self.headers[name] = header_set.to_header()
  1635. return parse_set_header(self.headers.get(name), on_update)
  1636. def fset(self, value):
  1637. if not value:
  1638. del self.headers[name]
  1639. elif isinstance(value, string_types):
  1640. self.headers[name] = value
  1641. else:
  1642. self.headers[name] = dump_header(value)
  1643. return property(fget, fset, doc=doc)
  1644. vary = _set_property('Vary', doc='''
  1645. The Vary field value indicates the set of request-header fields that
  1646. fully determines, while the response is fresh, whether a cache is
  1647. permitted to use the response to reply to a subsequent request
  1648. without revalidation.''')
  1649. content_language = _set_property('Content-Language', doc='''
  1650. The Content-Language entity-header field describes the natural
  1651. language(s) of the intended audience for the enclosed entity. Note
  1652. that this might not be equivalent to all the languages used within
  1653. the entity-body.''')
  1654. allow = _set_property('Allow', doc='''
  1655. The Allow entity-header field lists the set of methods supported
  1656. by the resource identified by the Request-URI. The purpose of this
  1657. field is strictly to inform the recipient of valid methods
  1658. associated with the resource. An Allow header field MUST be
  1659. present in a 405 (Method Not Allowed) response.''')
  1660. del _set_property, _get_mimetype, _set_mimetype, _get_retry_after, \
  1661. _set_retry_after
  1662. class WWWAuthenticateMixin(object):
  1663. """Adds a :attr:`www_authenticate` property to a response object."""
  1664. @property
  1665. def www_authenticate(self):
  1666. """The `WWW-Authenticate` header in a parsed form."""
  1667. def on_update(www_auth):
  1668. if not www_auth and 'www-authenticate' in self.headers:
  1669. del self.headers['www-authenticate']
  1670. elif www_auth:
  1671. self.headers['WWW-Authenticate'] = www_auth.to_header()
  1672. header = self.headers.get('www-authenticate')
  1673. return parse_www_authenticate_header(header, on_update)
  1674. class Request(BaseRequest, AcceptMixin, ETagRequestMixin,
  1675. UserAgentMixin, AuthorizationMixin,
  1676. CommonRequestDescriptorsMixin):
  1677. """Full featured request object implementing the following mixins:
  1678. - :class:`AcceptMixin` for accept header parsing
  1679. - :class:`ETagRequestMixin` for etag and cache control handling
  1680. - :class:`UserAgentMixin` for user agent introspection
  1681. - :class:`AuthorizationMixin` for http auth handling
  1682. - :class:`CommonRequestDescriptorsMixin` for common headers
  1683. """
  1684. class PlainRequest(StreamOnlyMixin, Request):
  1685. """A request object without special form parsing capabilities.
  1686. .. versionadded:: 0.9
  1687. """
  1688. class Response(BaseResponse, ETagResponseMixin, ResponseStreamMixin,
  1689. CommonResponseDescriptorsMixin,
  1690. WWWAuthenticateMixin):
  1691. """Full featured response object implementing the following mixins:
  1692. - :class:`ETagResponseMixin` for etag and cache control handling
  1693. - :class:`ResponseStreamMixin` to add support for the `stream` property
  1694. - :class:`CommonResponseDescriptorsMixin` for various HTTP descriptors
  1695. - :class:`WWWAuthenticateMixin` for HTTP authentication support
  1696. """