wrappers.py 75 KB

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