wrappers.py 77 KB

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