app.py 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.app
  4. ~~~~~~~~~
  5. This module implements the central WSGI application object.
  6. :copyright: (c) 2015 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import os
  10. import sys
  11. from threading import Lock
  12. from datetime import timedelta
  13. from itertools import chain
  14. from functools import update_wrapper
  15. from collections import deque
  16. from werkzeug.datastructures import ImmutableDict
  17. from werkzeug.routing import Map, Rule, RequestRedirect, BuildError
  18. from werkzeug.exceptions import HTTPException, InternalServerError, \
  19. MethodNotAllowed, BadRequest, default_exceptions
  20. from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \
  21. locked_cached_property, _endpoint_from_view_func, find_package, \
  22. get_debug_flag
  23. from . import json, cli
  24. from .wrappers import Request, Response
  25. from .config import ConfigAttribute, Config
  26. from .ctx import RequestContext, AppContext, _AppCtxGlobals
  27. from .globals import _request_ctx_stack, request, session, g
  28. from .sessions import SecureCookieSessionInterface
  29. from .templating import DispatchingJinjaLoader, Environment, \
  30. _default_template_ctx_processor
  31. from .signals import request_started, request_finished, got_request_exception, \
  32. request_tearing_down, appcontext_tearing_down
  33. from ._compat import reraise, string_types, text_type, integer_types
  34. # a lock used for logger initialization
  35. _logger_lock = Lock()
  36. # a singleton sentinel value for parameter defaults
  37. _sentinel = object()
  38. def _make_timedelta(value):
  39. if not isinstance(value, timedelta):
  40. return timedelta(seconds=value)
  41. return value
  42. def setupmethod(f):
  43. """Wraps a method so that it performs a check in debug mode if the
  44. first request was already handled.
  45. """
  46. def wrapper_func(self, *args, **kwargs):
  47. if self.debug and self._got_first_request:
  48. raise AssertionError('A setup function was called after the '
  49. 'first request was handled. This usually indicates a bug '
  50. 'in the application where a module was not imported '
  51. 'and decorators or other functionality was called too late.\n'
  52. 'To fix this make sure to import all your view modules, '
  53. 'database models and everything related at a central place '
  54. 'before the application starts serving requests.')
  55. return f(self, *args, **kwargs)
  56. return update_wrapper(wrapper_func, f)
  57. class Flask(_PackageBoundObject):
  58. """The flask object implements a WSGI application and acts as the central
  59. object. It is passed the name of the module or package of the
  60. application. Once it is created it will act as a central registry for
  61. the view functions, the URL rules, template configuration and much more.
  62. The name of the package is used to resolve resources from inside the
  63. package or the folder the module is contained in depending on if the
  64. package parameter resolves to an actual python package (a folder with
  65. an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
  66. For more information about resource loading, see :func:`open_resource`.
  67. Usually you create a :class:`Flask` instance in your main module or
  68. in the :file:`__init__.py` file of your package like this::
  69. from flask import Flask
  70. app = Flask(__name__)
  71. .. admonition:: About the First Parameter
  72. The idea of the first parameter is to give Flask an idea of what
  73. belongs to your application. This name is used to find resources
  74. on the filesystem, can be used by extensions to improve debugging
  75. information and a lot more.
  76. So it's important what you provide there. If you are using a single
  77. module, `__name__` is always the correct value. If you however are
  78. using a package, it's usually recommended to hardcode the name of
  79. your package there.
  80. For example if your application is defined in :file:`yourapplication/app.py`
  81. you should create it with one of the two versions below::
  82. app = Flask('yourapplication')
  83. app = Flask(__name__.split('.')[0])
  84. Why is that? The application will work even with `__name__`, thanks
  85. to how resources are looked up. However it will make debugging more
  86. painful. Certain extensions can make assumptions based on the
  87. import name of your application. For example the Flask-SQLAlchemy
  88. extension will look for the code in your application that triggered
  89. an SQL query in debug mode. If the import name is not properly set
  90. up, that debugging information is lost. (For example it would only
  91. pick up SQL queries in `yourapplication.app` and not
  92. `yourapplication.views.frontend`)
  93. .. versionadded:: 0.7
  94. The `static_url_path`, `static_folder`, and `template_folder`
  95. parameters were added.
  96. .. versionadded:: 0.8
  97. The `instance_path` and `instance_relative_config` parameters were
  98. added.
  99. .. versionadded:: 0.11
  100. The `root_path` parameter was added.
  101. :param import_name: the name of the application package
  102. :param static_url_path: can be used to specify a different path for the
  103. static files on the web. Defaults to the name
  104. of the `static_folder` folder.
  105. :param static_folder: the folder with static files that should be served
  106. at `static_url_path`. Defaults to the ``'static'``
  107. folder in the root path of the application.
  108. :param template_folder: the folder that contains the templates that should
  109. be used by the application. Defaults to
  110. ``'templates'`` folder in the root path of the
  111. application.
  112. :param instance_path: An alternative instance path for the application.
  113. By default the folder ``'instance'`` next to the
  114. package or module is assumed to be the instance
  115. path.
  116. :param instance_relative_config: if set to ``True`` relative filenames
  117. for loading the config are assumed to
  118. be relative to the instance path instead
  119. of the application root.
  120. :param root_path: Flask by default will automatically calculate the path
  121. to the root of the application. In certain situations
  122. this cannot be achieved (for instance if the package
  123. is a Python 3 namespace package) and needs to be
  124. manually defined.
  125. """
  126. #: The class that is used for request objects. See :class:`~flask.Request`
  127. #: for more information.
  128. request_class = Request
  129. #: The class that is used for response objects. See
  130. #: :class:`~flask.Response` for more information.
  131. response_class = Response
  132. #: The class that is used for the Jinja environment.
  133. #:
  134. #: .. versionadded:: 0.11
  135. jinja_environment = Environment
  136. #: The class that is used for the :data:`~flask.g` instance.
  137. #:
  138. #: Example use cases for a custom class:
  139. #:
  140. #: 1. Store arbitrary attributes on flask.g.
  141. #: 2. Add a property for lazy per-request database connectors.
  142. #: 3. Return None instead of AttributeError on unexpected attributes.
  143. #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.
  144. #:
  145. #: In Flask 0.9 this property was called `request_globals_class` but it
  146. #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the
  147. #: flask.g object is now application context scoped.
  148. #:
  149. #: .. versionadded:: 0.10
  150. app_ctx_globals_class = _AppCtxGlobals
  151. # Backwards compatibility support
  152. def _get_request_globals_class(self):
  153. return self.app_ctx_globals_class
  154. def _set_request_globals_class(self, value):
  155. from warnings import warn
  156. warn(DeprecationWarning('request_globals_class attribute is now '
  157. 'called app_ctx_globals_class'))
  158. self.app_ctx_globals_class = value
  159. request_globals_class = property(_get_request_globals_class,
  160. _set_request_globals_class)
  161. del _get_request_globals_class, _set_request_globals_class
  162. #: The class that is used for the ``config`` attribute of this app.
  163. #: Defaults to :class:`~flask.Config`.
  164. #:
  165. #: Example use cases for a custom class:
  166. #:
  167. #: 1. Default values for certain config options.
  168. #: 2. Access to config values through attributes in addition to keys.
  169. #:
  170. #: .. versionadded:: 0.11
  171. config_class = Config
  172. #: The debug flag. Set this to ``True`` to enable debugging of the
  173. #: application. In debug mode the debugger will kick in when an unhandled
  174. #: exception occurs and the integrated server will automatically reload
  175. #: the application if changes in the code are detected.
  176. #:
  177. #: This attribute can also be configured from the config with the ``DEBUG``
  178. #: configuration key. Defaults to ``False``.
  179. debug = ConfigAttribute('DEBUG')
  180. #: The testing flag. Set this to ``True`` to enable the test mode of
  181. #: Flask extensions (and in the future probably also Flask itself).
  182. #: For example this might activate unittest helpers that have an
  183. #: additional runtime cost which should not be enabled by default.
  184. #:
  185. #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
  186. #: default it's implicitly enabled.
  187. #:
  188. #: This attribute can also be configured from the config with the
  189. #: ``TESTING`` configuration key. Defaults to ``False``.
  190. testing = ConfigAttribute('TESTING')
  191. #: If a secret key is set, cryptographic components can use this to
  192. #: sign cookies and other things. Set this to a complex random value
  193. #: when you want to use the secure cookie for instance.
  194. #:
  195. #: This attribute can also be configured from the config with the
  196. #: ``SECRET_KEY`` configuration key. Defaults to ``None``.
  197. secret_key = ConfigAttribute('SECRET_KEY')
  198. #: The secure cookie uses this for the name of the session cookie.
  199. #:
  200. #: This attribute can also be configured from the config with the
  201. #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``
  202. session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')
  203. #: A :class:`~datetime.timedelta` which is used to set the expiration
  204. #: date of a permanent session. The default is 31 days which makes a
  205. #: permanent session survive for roughly one month.
  206. #:
  207. #: This attribute can also be configured from the config with the
  208. #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to
  209. #: ``timedelta(days=31)``
  210. permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME',
  211. get_converter=_make_timedelta)
  212. #: A :class:`~datetime.timedelta` which is used as default cache_timeout
  213. #: for the :func:`send_file` functions. The default is 12 hours.
  214. #:
  215. #: This attribute can also be configured from the config with the
  216. #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration
  217. #: variable can also be set with an integer value used as seconds.
  218. #: Defaults to ``timedelta(hours=12)``
  219. send_file_max_age_default = ConfigAttribute('SEND_FILE_MAX_AGE_DEFAULT',
  220. get_converter=_make_timedelta)
  221. #: Enable this if you want to use the X-Sendfile feature. Keep in
  222. #: mind that the server has to support this. This only affects files
  223. #: sent with the :func:`send_file` method.
  224. #:
  225. #: .. versionadded:: 0.2
  226. #:
  227. #: This attribute can also be configured from the config with the
  228. #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.
  229. use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')
  230. #: The name of the logger to use. By default the logger name is the
  231. #: package name passed to the constructor.
  232. #:
  233. #: .. versionadded:: 0.4
  234. logger_name = ConfigAttribute('LOGGER_NAME')
  235. #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.
  236. #:
  237. #: .. versionadded:: 0.10
  238. json_encoder = json.JSONEncoder
  239. #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.
  240. #:
  241. #: .. versionadded:: 0.10
  242. json_decoder = json.JSONDecoder
  243. #: Options that are passed directly to the Jinja2 environment.
  244. jinja_options = ImmutableDict(
  245. extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']
  246. )
  247. #: Default configuration parameters.
  248. default_config = ImmutableDict({
  249. 'DEBUG': get_debug_flag(default=False),
  250. 'TESTING': False,
  251. 'PROPAGATE_EXCEPTIONS': None,
  252. 'PRESERVE_CONTEXT_ON_EXCEPTION': None,
  253. 'SECRET_KEY': None,
  254. 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
  255. 'USE_X_SENDFILE': False,
  256. 'LOGGER_NAME': None,
  257. 'LOGGER_HANDLER_POLICY': 'always',
  258. 'SERVER_NAME': None,
  259. 'APPLICATION_ROOT': None,
  260. 'SESSION_COOKIE_NAME': 'session',
  261. 'SESSION_COOKIE_DOMAIN': None,
  262. 'SESSION_COOKIE_PATH': None,
  263. 'SESSION_COOKIE_HTTPONLY': True,
  264. 'SESSION_COOKIE_SECURE': False,
  265. 'SESSION_REFRESH_EACH_REQUEST': True,
  266. 'MAX_CONTENT_LENGTH': None,
  267. 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),
  268. 'TRAP_BAD_REQUEST_ERRORS': False,
  269. 'TRAP_HTTP_EXCEPTIONS': False,
  270. 'EXPLAIN_TEMPLATE_LOADING': False,
  271. 'PREFERRED_URL_SCHEME': 'http',
  272. 'JSON_AS_ASCII': True,
  273. 'JSON_SORT_KEYS': True,
  274. 'JSONIFY_PRETTYPRINT_REGULAR': True,
  275. 'JSONIFY_MIMETYPE': 'application/json',
  276. 'TEMPLATES_AUTO_RELOAD': None,
  277. })
  278. #: The rule object to use for URL rules created. This is used by
  279. #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.
  280. #:
  281. #: .. versionadded:: 0.7
  282. url_rule_class = Rule
  283. #: the test client that is used with when `test_client` is used.
  284. #:
  285. #: .. versionadded:: 0.7
  286. test_client_class = None
  287. #: the session interface to use. By default an instance of
  288. #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.
  289. #:
  290. #: .. versionadded:: 0.8
  291. session_interface = SecureCookieSessionInterface()
  292. def __init__(self, import_name, static_path=None, static_url_path=None,
  293. static_folder='static', template_folder='templates',
  294. instance_path=None, instance_relative_config=False,
  295. root_path=None):
  296. _PackageBoundObject.__init__(self, import_name,
  297. template_folder=template_folder,
  298. root_path=root_path)
  299. if static_path is not None:
  300. from warnings import warn
  301. warn(DeprecationWarning('static_path is now called '
  302. 'static_url_path'), stacklevel=2)
  303. static_url_path = static_path
  304. if static_url_path is not None:
  305. self.static_url_path = static_url_path
  306. if static_folder is not None:
  307. self.static_folder = static_folder
  308. if instance_path is None:
  309. instance_path = self.auto_find_instance_path()
  310. elif not os.path.isabs(instance_path):
  311. raise ValueError('If an instance path is provided it must be '
  312. 'absolute. A relative path was given instead.')
  313. #: Holds the path to the instance folder.
  314. #:
  315. #: .. versionadded:: 0.8
  316. self.instance_path = instance_path
  317. #: The configuration dictionary as :class:`Config`. This behaves
  318. #: exactly like a regular dictionary but supports additional methods
  319. #: to load a config from files.
  320. self.config = self.make_config(instance_relative_config)
  321. # Prepare the deferred setup of the logger.
  322. self._logger = None
  323. self.logger_name = self.import_name
  324. #: A dictionary of all view functions registered. The keys will
  325. #: be function names which are also used to generate URLs and
  326. #: the values are the function objects themselves.
  327. #: To register a view function, use the :meth:`route` decorator.
  328. self.view_functions = {}
  329. # support for the now deprecated `error_handlers` attribute. The
  330. # :attr:`error_handler_spec` shall be used now.
  331. self._error_handlers = {}
  332. #: A dictionary of all registered error handlers. The key is ``None``
  333. #: for error handlers active on the application, otherwise the key is
  334. #: the name of the blueprint. Each key points to another dictionary
  335. #: where the key is the status code of the http exception. The
  336. #: special key ``None`` points to a list of tuples where the first item
  337. #: is the class for the instance check and the second the error handler
  338. #: function.
  339. #:
  340. #: To register a error handler, use the :meth:`errorhandler`
  341. #: decorator.
  342. self.error_handler_spec = {None: self._error_handlers}
  343. #: A list of functions that are called when :meth:`url_for` raises a
  344. #: :exc:`~werkzeug.routing.BuildError`. Each function registered here
  345. #: is called with `error`, `endpoint` and `values`. If a function
  346. #: returns ``None`` or raises a :exc:`BuildError` the next function is
  347. #: tried.
  348. #:
  349. #: .. versionadded:: 0.9
  350. self.url_build_error_handlers = []
  351. #: A dictionary with lists of functions that should be called at the
  352. #: beginning of the request. The key of the dictionary is the name of
  353. #: the blueprint this function is active for, ``None`` for all requests.
  354. #: This can for example be used to open database connections or
  355. #: getting hold of the currently logged in user. To register a
  356. #: function here, use the :meth:`before_request` decorator.
  357. self.before_request_funcs = {}
  358. #: A lists of functions that should be called at the beginning of the
  359. #: first request to this instance. To register a function here, use
  360. #: the :meth:`before_first_request` decorator.
  361. #:
  362. #: .. versionadded:: 0.8
  363. self.before_first_request_funcs = []
  364. #: A dictionary with lists of functions that should be called after
  365. #: each request. The key of the dictionary is the name of the blueprint
  366. #: this function is active for, ``None`` for all requests. This can for
  367. #: example be used to close database connections. To register a function
  368. #: here, use the :meth:`after_request` decorator.
  369. self.after_request_funcs = {}
  370. #: A dictionary with lists of functions that are called after
  371. #: each request, even if an exception has occurred. The key of the
  372. #: dictionary is the name of the blueprint this function is active for,
  373. #: ``None`` for all requests. These functions are not allowed to modify
  374. #: the request, and their return values are ignored. If an exception
  375. #: occurred while processing the request, it gets passed to each
  376. #: teardown_request function. To register a function here, use the
  377. #: :meth:`teardown_request` decorator.
  378. #:
  379. #: .. versionadded:: 0.7
  380. self.teardown_request_funcs = {}
  381. #: A list of functions that are called when the application context
  382. #: is destroyed. Since the application context is also torn down
  383. #: if the request ends this is the place to store code that disconnects
  384. #: from databases.
  385. #:
  386. #: .. versionadded:: 0.9
  387. self.teardown_appcontext_funcs = []
  388. #: A dictionary with lists of functions that can be used as URL
  389. #: value processor functions. Whenever a URL is built these functions
  390. #: are called to modify the dictionary of values in place. The key
  391. #: ``None`` here is used for application wide
  392. #: callbacks, otherwise the key is the name of the blueprint.
  393. #: Each of these functions has the chance to modify the dictionary
  394. #:
  395. #: .. versionadded:: 0.7
  396. self.url_value_preprocessors = {}
  397. #: A dictionary with lists of functions that can be used as URL value
  398. #: preprocessors. The key ``None`` here is used for application wide
  399. #: callbacks, otherwise the key is the name of the blueprint.
  400. #: Each of these functions has the chance to modify the dictionary
  401. #: of URL values before they are used as the keyword arguments of the
  402. #: view function. For each function registered this one should also
  403. #: provide a :meth:`url_defaults` function that adds the parameters
  404. #: automatically again that were removed that way.
  405. #:
  406. #: .. versionadded:: 0.7
  407. self.url_default_functions = {}
  408. #: A dictionary with list of functions that are called without argument
  409. #: to populate the template context. The key of the dictionary is the
  410. #: name of the blueprint this function is active for, ``None`` for all
  411. #: requests. Each returns a dictionary that the template context is
  412. #: updated with. To register a function here, use the
  413. #: :meth:`context_processor` decorator.
  414. self.template_context_processors = {
  415. None: [_default_template_ctx_processor]
  416. }
  417. #: A list of shell context processor functions that should be run
  418. #: when a shell context is created.
  419. #:
  420. #: .. versionadded:: 0.11
  421. self.shell_context_processors = []
  422. #: all the attached blueprints in a dictionary by name. Blueprints
  423. #: can be attached multiple times so this dictionary does not tell
  424. #: you how often they got attached.
  425. #:
  426. #: .. versionadded:: 0.7
  427. self.blueprints = {}
  428. self._blueprint_order = []
  429. #: a place where extensions can store application specific state. For
  430. #: example this is where an extension could store database engines and
  431. #: similar things. For backwards compatibility extensions should register
  432. #: themselves like this::
  433. #:
  434. #: if not hasattr(app, 'extensions'):
  435. #: app.extensions = {}
  436. #: app.extensions['extensionname'] = SomeObject()
  437. #:
  438. #: The key must match the name of the extension module. For example in
  439. #: case of a "Flask-Foo" extension in `flask_foo`, the key would be
  440. #: ``'foo'``.
  441. #:
  442. #: .. versionadded:: 0.7
  443. self.extensions = {}
  444. #: The :class:`~werkzeug.routing.Map` for this instance. You can use
  445. #: this to change the routing converters after the class was created
  446. #: but before any routes are connected. Example::
  447. #:
  448. #: from werkzeug.routing import BaseConverter
  449. #:
  450. #: class ListConverter(BaseConverter):
  451. #: def to_python(self, value):
  452. #: return value.split(',')
  453. #: def to_url(self, values):
  454. #: return ','.join(BaseConverter.to_url(value)
  455. #: for value in values)
  456. #:
  457. #: app = Flask(__name__)
  458. #: app.url_map.converters['list'] = ListConverter
  459. self.url_map = Map()
  460. # tracks internally if the application already handled at least one
  461. # request.
  462. self._got_first_request = False
  463. self._before_request_lock = Lock()
  464. # register the static folder for the application. Do that even
  465. # if the folder does not exist. First of all it might be created
  466. # while the server is running (usually happens during development)
  467. # but also because google appengine stores static files somewhere
  468. # else when mapped with the .yml file.
  469. if self.has_static_folder:
  470. self.add_url_rule(self.static_url_path + '/<path:filename>',
  471. endpoint='static',
  472. view_func=self.send_static_file)
  473. #: The click command line context for this application. Commands
  474. #: registered here show up in the :command:`flask` command once the
  475. #: application has been discovered. The default commands are
  476. #: provided by Flask itself and can be overridden.
  477. #:
  478. #: This is an instance of a :class:`click.Group` object.
  479. self.cli = cli.AppGroup(self.name)
  480. def _get_error_handlers(self):
  481. from warnings import warn
  482. warn(DeprecationWarning('error_handlers is deprecated, use the '
  483. 'new error_handler_spec attribute instead.'), stacklevel=1)
  484. return self._error_handlers
  485. def _set_error_handlers(self, value):
  486. self._error_handlers = value
  487. self.error_handler_spec[None] = value
  488. error_handlers = property(_get_error_handlers, _set_error_handlers)
  489. del _get_error_handlers, _set_error_handlers
  490. @locked_cached_property
  491. def name(self):
  492. """The name of the application. This is usually the import name
  493. with the difference that it's guessed from the run file if the
  494. import name is main. This name is used as a display name when
  495. Flask needs the name of the application. It can be set and overridden
  496. to change the value.
  497. .. versionadded:: 0.8
  498. """
  499. if self.import_name == '__main__':
  500. fn = getattr(sys.modules['__main__'], '__file__', None)
  501. if fn is None:
  502. return '__main__'
  503. return os.path.splitext(os.path.basename(fn))[0]
  504. return self.import_name
  505. @property
  506. def propagate_exceptions(self):
  507. """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration
  508. value in case it's set, otherwise a sensible default is returned.
  509. .. versionadded:: 0.7
  510. """
  511. rv = self.config['PROPAGATE_EXCEPTIONS']
  512. if rv is not None:
  513. return rv
  514. return self.testing or self.debug
  515. @property
  516. def preserve_context_on_exception(self):
  517. """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``
  518. configuration value in case it's set, otherwise a sensible default
  519. is returned.
  520. .. versionadded:: 0.7
  521. """
  522. rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION']
  523. if rv is not None:
  524. return rv
  525. return self.debug
  526. @property
  527. def logger(self):
  528. """A :class:`logging.Logger` object for this application. The
  529. default configuration is to log to stderr if the application is
  530. in debug mode. This logger can be used to (surprise) log messages.
  531. Here some examples::
  532. app.logger.debug('A value for debugging')
  533. app.logger.warning('A warning occurred (%d apples)', 42)
  534. app.logger.error('An error occurred')
  535. .. versionadded:: 0.3
  536. """
  537. if self._logger and self._logger.name == self.logger_name:
  538. return self._logger
  539. with _logger_lock:
  540. if self._logger and self._logger.name == self.logger_name:
  541. return self._logger
  542. from flask.logging import create_logger
  543. self._logger = rv = create_logger(self)
  544. return rv
  545. @locked_cached_property
  546. def jinja_env(self):
  547. """The Jinja2 environment used to load templates."""
  548. return self.create_jinja_environment()
  549. @property
  550. def got_first_request(self):
  551. """This attribute is set to ``True`` if the application started
  552. handling the first request.
  553. .. versionadded:: 0.8
  554. """
  555. return self._got_first_request
  556. def make_config(self, instance_relative=False):
  557. """Used to create the config attribute by the Flask constructor.
  558. The `instance_relative` parameter is passed in from the constructor
  559. of Flask (there named `instance_relative_config`) and indicates if
  560. the config should be relative to the instance path or the root path
  561. of the application.
  562. .. versionadded:: 0.8
  563. """
  564. root_path = self.root_path
  565. if instance_relative:
  566. root_path = self.instance_path
  567. return self.config_class(root_path, self.default_config)
  568. def auto_find_instance_path(self):
  569. """Tries to locate the instance path if it was not provided to the
  570. constructor of the application class. It will basically calculate
  571. the path to a folder named ``instance`` next to your main file or
  572. the package.
  573. .. versionadded:: 0.8
  574. """
  575. prefix, package_path = find_package(self.import_name)
  576. if prefix is None:
  577. return os.path.join(package_path, 'instance')
  578. return os.path.join(prefix, 'var', self.name + '-instance')
  579. def open_instance_resource(self, resource, mode='rb'):
  580. """Opens a resource from the application's instance folder
  581. (:attr:`instance_path`). Otherwise works like
  582. :meth:`open_resource`. Instance resources can also be opened for
  583. writing.
  584. :param resource: the name of the resource. To access resources within
  585. subfolders use forward slashes as separator.
  586. :param mode: resource file opening mode, default is 'rb'.
  587. """
  588. return open(os.path.join(self.instance_path, resource), mode)
  589. def create_jinja_environment(self):
  590. """Creates the Jinja2 environment based on :attr:`jinja_options`
  591. and :meth:`select_jinja_autoescape`. Since 0.7 this also adds
  592. the Jinja2 globals and filters after initialization. Override
  593. this function to customize the behavior.
  594. .. versionadded:: 0.5
  595. .. versionchanged:: 0.11
  596. ``Environment.auto_reload`` set in accordance with
  597. ``TEMPLATES_AUTO_RELOAD`` configuration option.
  598. """
  599. options = dict(self.jinja_options)
  600. if 'autoescape' not in options:
  601. options['autoescape'] = self.select_jinja_autoescape
  602. if 'auto_reload' not in options:
  603. if self.config['TEMPLATES_AUTO_RELOAD'] is not None:
  604. options['auto_reload'] = self.config['TEMPLATES_AUTO_RELOAD']
  605. else:
  606. options['auto_reload'] = self.debug
  607. rv = self.jinja_environment(self, **options)
  608. rv.globals.update(
  609. url_for=url_for,
  610. get_flashed_messages=get_flashed_messages,
  611. config=self.config,
  612. # request, session and g are normally added with the
  613. # context processor for efficiency reasons but for imported
  614. # templates we also want the proxies in there.
  615. request=request,
  616. session=session,
  617. g=g
  618. )
  619. rv.filters['tojson'] = json.tojson_filter
  620. return rv
  621. def create_global_jinja_loader(self):
  622. """Creates the loader for the Jinja2 environment. Can be used to
  623. override just the loader and keeping the rest unchanged. It's
  624. discouraged to override this function. Instead one should override
  625. the :meth:`jinja_loader` function instead.
  626. The global loader dispatches between the loaders of the application
  627. and the individual blueprints.
  628. .. versionadded:: 0.7
  629. """
  630. return DispatchingJinjaLoader(self)
  631. def init_jinja_globals(self):
  632. """Deprecated. Used to initialize the Jinja2 globals.
  633. .. versionadded:: 0.5
  634. .. versionchanged:: 0.7
  635. This method is deprecated with 0.7. Override
  636. :meth:`create_jinja_environment` instead.
  637. """
  638. def select_jinja_autoescape(self, filename):
  639. """Returns ``True`` if autoescaping should be active for the given
  640. template name. If no template name is given, returns `True`.
  641. .. versionadded:: 0.5
  642. """
  643. if filename is None:
  644. return True
  645. return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))
  646. def update_template_context(self, context):
  647. """Update the template context with some commonly used variables.
  648. This injects request, session, config and g into the template
  649. context as well as everything template context processors want
  650. to inject. Note that the as of Flask 0.6, the original values
  651. in the context will not be overridden if a context processor
  652. decides to return a value with the same key.
  653. :param context: the context as a dictionary that is updated in place
  654. to add extra variables.
  655. """
  656. funcs = self.template_context_processors[None]
  657. reqctx = _request_ctx_stack.top
  658. if reqctx is not None:
  659. bp = reqctx.request.blueprint
  660. if bp is not None and bp in self.template_context_processors:
  661. funcs = chain(funcs, self.template_context_processors[bp])
  662. orig_ctx = context.copy()
  663. for func in funcs:
  664. context.update(func())
  665. # make sure the original values win. This makes it possible to
  666. # easier add new variables in context processors without breaking
  667. # existing views.
  668. context.update(orig_ctx)
  669. def make_shell_context(self):
  670. """Returns the shell context for an interactive shell for this
  671. application. This runs all the registered shell context
  672. processors.
  673. .. versionadded:: 0.11
  674. """
  675. rv = {'app': self, 'g': g}
  676. for processor in self.shell_context_processors:
  677. rv.update(processor())
  678. return rv
  679. def run(self, host=None, port=None, debug=None, **options):
  680. """Runs the application on a local development server.
  681. Do not use ``run()`` in a production setting. It is not intended to
  682. meet security and performance requirements for a production server.
  683. Instead, see :ref:`deployment` for WSGI server recommendations.
  684. If the :attr:`debug` flag is set the server will automatically reload
  685. for code changes and show a debugger in case an exception happened.
  686. If you want to run the application in debug mode, but disable the
  687. code execution on the interactive debugger, you can pass
  688. ``use_evalex=False`` as parameter. This will keep the debugger's
  689. traceback screen active, but disable code execution.
  690. It is not recommended to use this function for development with
  691. automatic reloading as this is badly supported. Instead you should
  692. be using the :command:`flask` command line script's ``run`` support.
  693. .. admonition:: Keep in Mind
  694. Flask will suppress any server error with a generic error page
  695. unless it is in debug mode. As such to enable just the
  696. interactive debugger without the code reloading, you have to
  697. invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
  698. Setting ``use_debugger`` to ``True`` without being in debug mode
  699. won't catch any exceptions because there won't be any to
  700. catch.
  701. .. versionchanged:: 0.10
  702. The default port is now picked from the ``SERVER_NAME`` variable.
  703. :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
  704. have the server available externally as well. Defaults to
  705. ``'127.0.0.1'``.
  706. :param port: the port of the webserver. Defaults to ``5000`` or the
  707. port defined in the ``SERVER_NAME`` config variable if
  708. present.
  709. :param debug: if given, enable or disable debug mode.
  710. See :attr:`debug`.
  711. :param options: the options to be forwarded to the underlying
  712. Werkzeug server. See
  713. :func:`werkzeug.serving.run_simple` for more
  714. information.
  715. """
  716. from werkzeug.serving import run_simple
  717. if host is None:
  718. host = '127.0.0.1'
  719. if port is None:
  720. server_name = self.config['SERVER_NAME']
  721. if server_name and ':' in server_name:
  722. port = int(server_name.rsplit(':', 1)[1])
  723. else:
  724. port = 5000
  725. if debug is not None:
  726. self.debug = bool(debug)
  727. options.setdefault('use_reloader', self.debug)
  728. options.setdefault('use_debugger', self.debug)
  729. options.setdefault('passthrough_errors', True)
  730. try:
  731. run_simple(host, port, self, **options)
  732. finally:
  733. # reset the first request information if the development server
  734. # resetted normally. This makes it possible to restart the server
  735. # without reloader and that stuff from an interactive shell.
  736. self._got_first_request = False
  737. def test_client(self, use_cookies=True, **kwargs):
  738. """Creates a test client for this application. For information
  739. about unit testing head over to :ref:`testing`.
  740. Note that if you are testing for assertions or exceptions in your
  741. application code, you must set ``app.testing = True`` in order for the
  742. exceptions to propagate to the test client. Otherwise, the exception
  743. will be handled by the application (not visible to the test client) and
  744. the only indication of an AssertionError or other exception will be a
  745. 500 status code response to the test client. See the :attr:`testing`
  746. attribute. For example::
  747. app.testing = True
  748. client = app.test_client()
  749. The test client can be used in a ``with`` block to defer the closing down
  750. of the context until the end of the ``with`` block. This is useful if
  751. you want to access the context locals for testing::
  752. with app.test_client() as c:
  753. rv = c.get('/?vodka=42')
  754. assert request.args['vodka'] == '42'
  755. Additionally, you may pass optional keyword arguments that will then
  756. be passed to the application's :attr:`test_client_class` constructor.
  757. For example::
  758. from flask.testing import FlaskClient
  759. class CustomClient(FlaskClient):
  760. def __init__(self, authentication=None, *args, **kwargs):
  761. FlaskClient.__init__(*args, **kwargs)
  762. self._authentication = authentication
  763. app.test_client_class = CustomClient
  764. client = app.test_client(authentication='Basic ....')
  765. See :class:`~flask.testing.FlaskClient` for more information.
  766. .. versionchanged:: 0.4
  767. added support for ``with`` block usage for the client.
  768. .. versionadded:: 0.7
  769. The `use_cookies` parameter was added as well as the ability
  770. to override the client to be used by setting the
  771. :attr:`test_client_class` attribute.
  772. .. versionchanged:: 0.11
  773. Added `**kwargs` to support passing additional keyword arguments to
  774. the constructor of :attr:`test_client_class`.
  775. """
  776. cls = self.test_client_class
  777. if cls is None:
  778. from flask.testing import FlaskClient as cls
  779. return cls(self, self.response_class, use_cookies=use_cookies, **kwargs)
  780. def open_session(self, request):
  781. """Creates or opens a new session. Default implementation stores all
  782. session data in a signed cookie. This requires that the
  783. :attr:`secret_key` is set. Instead of overriding this method
  784. we recommend replacing the :class:`session_interface`.
  785. :param request: an instance of :attr:`request_class`.
  786. """
  787. return self.session_interface.open_session(self, request)
  788. def save_session(self, session, response):
  789. """Saves the session if it needs updates. For the default
  790. implementation, check :meth:`open_session`. Instead of overriding this
  791. method we recommend replacing the :class:`session_interface`.
  792. :param session: the session to be saved (a
  793. :class:`~werkzeug.contrib.securecookie.SecureCookie`
  794. object)
  795. :param response: an instance of :attr:`response_class`
  796. """
  797. return self.session_interface.save_session(self, session, response)
  798. def make_null_session(self):
  799. """Creates a new instance of a missing session. Instead of overriding
  800. this method we recommend replacing the :class:`session_interface`.
  801. .. versionadded:: 0.7
  802. """
  803. return self.session_interface.make_null_session(self)
  804. @setupmethod
  805. def register_blueprint(self, blueprint, **options):
  806. """Register a blueprint on the application. For information about
  807. blueprints head over to :ref:`blueprints`.
  808. The blueprint name is passed in as the first argument.
  809. Options are passed as additional keyword arguments and forwarded to
  810. `blueprints` in an "options" dictionary.
  811. :param subdomain: set a subdomain for the blueprint
  812. :param url_prefix: set the prefix for all URLs defined on the blueprint.
  813. ``(url_prefix='/<lang code>')``
  814. :param url_defaults: a dictionary with URL defaults that is added to
  815. each and every URL defined with this blueprint
  816. :param static_folder: add a static folder to urls in this blueprint
  817. :param static_url_path: add a static url path to urls in this blueprint
  818. :param template_folder: set an alternate template folder
  819. :param root_path: set an alternate root path for this blueprint
  820. .. versionadded:: 0.7
  821. """
  822. first_registration = False
  823. if blueprint.name in self.blueprints:
  824. assert self.blueprints[blueprint.name] is blueprint, \
  825. 'A blueprint\'s name collision occurred between %r and ' \
  826. '%r. Both share the same name "%s". Blueprints that ' \
  827. 'are created on the fly need unique names.' % \
  828. (blueprint, self.blueprints[blueprint.name], blueprint.name)
  829. else:
  830. self.blueprints[blueprint.name] = blueprint
  831. self._blueprint_order.append(blueprint)
  832. first_registration = True
  833. blueprint.register(self, options, first_registration)
  834. def iter_blueprints(self):
  835. """Iterates over all blueprints by the order they were registered.
  836. .. versionadded:: 0.11
  837. """
  838. return iter(self._blueprint_order)
  839. @setupmethod
  840. def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
  841. """Connects a URL rule. Works exactly like the :meth:`route`
  842. decorator. If a view_func is provided it will be registered with the
  843. endpoint.
  844. Basically this example::
  845. @app.route('/')
  846. def index():
  847. pass
  848. Is equivalent to the following::
  849. def index():
  850. pass
  851. app.add_url_rule('/', 'index', index)
  852. If the view_func is not provided you will need to connect the endpoint
  853. to a view function like so::
  854. app.view_functions['index'] = index
  855. Internally :meth:`route` invokes :meth:`add_url_rule` so if you want
  856. to customize the behavior via subclassing you only need to change
  857. this method.
  858. For more information refer to :ref:`url-route-registrations`.
  859. .. versionchanged:: 0.2
  860. `view_func` parameter added.
  861. .. versionchanged:: 0.6
  862. ``OPTIONS`` is added automatically as method.
  863. :param rule: the URL rule as string
  864. :param endpoint: the endpoint for the registered URL rule. Flask
  865. itself assumes the name of the view function as
  866. endpoint
  867. :param view_func: the function to call when serving a request to the
  868. provided endpoint
  869. :param options: the options to be forwarded to the underlying
  870. :class:`~werkzeug.routing.Rule` object. A change
  871. to Werkzeug is handling of method options. methods
  872. is a list of methods this rule should be limited
  873. to (``GET``, ``POST`` etc.). By default a rule
  874. just listens for ``GET`` (and implicitly ``HEAD``).
  875. Starting with Flask 0.6, ``OPTIONS`` is implicitly
  876. added and handled by the standard request handling.
  877. """
  878. if endpoint is None:
  879. endpoint = _endpoint_from_view_func(view_func)
  880. options['endpoint'] = endpoint
  881. methods = options.pop('methods', None)
  882. # if the methods are not given and the view_func object knows its
  883. # methods we can use that instead. If neither exists, we go with
  884. # a tuple of only ``GET`` as default.
  885. if methods is None:
  886. methods = getattr(view_func, 'methods', None) or ('GET',)
  887. if isinstance(methods, string_types):
  888. raise TypeError('Allowed methods have to be iterables of strings, '
  889. 'for example: @app.route(..., methods=["POST"])')
  890. methods = set(item.upper() for item in methods)
  891. # Methods that should always be added
  892. required_methods = set(getattr(view_func, 'required_methods', ()))
  893. # starting with Flask 0.8 the view_func object can disable and
  894. # force-enable the automatic options handling.
  895. provide_automatic_options = getattr(view_func,
  896. 'provide_automatic_options', None)
  897. if provide_automatic_options is None:
  898. if 'OPTIONS' not in methods:
  899. provide_automatic_options = True
  900. required_methods.add('OPTIONS')
  901. else:
  902. provide_automatic_options = False
  903. # Add the required methods now.
  904. methods |= required_methods
  905. rule = self.url_rule_class(rule, methods=methods, **options)
  906. rule.provide_automatic_options = provide_automatic_options
  907. self.url_map.add(rule)
  908. if view_func is not None:
  909. old_func = self.view_functions.get(endpoint)
  910. if old_func is not None and old_func != view_func:
  911. raise AssertionError('View function mapping is overwriting an '
  912. 'existing endpoint function: %s' % endpoint)
  913. self.view_functions[endpoint] = view_func
  914. def route(self, rule, **options):
  915. """A decorator that is used to register a view function for a
  916. given URL rule. This does the same thing as :meth:`add_url_rule`
  917. but is intended for decorator usage::
  918. @app.route('/')
  919. def index():
  920. return 'Hello World'
  921. For more information refer to :ref:`url-route-registrations`.
  922. :param rule: the URL rule as string
  923. :param endpoint: the endpoint for the registered URL rule. Flask
  924. itself assumes the name of the view function as
  925. endpoint
  926. :param options: the options to be forwarded to the underlying
  927. :class:`~werkzeug.routing.Rule` object. A change
  928. to Werkzeug is handling of method options. methods
  929. is a list of methods this rule should be limited
  930. to (``GET``, ``POST`` etc.). By default a rule
  931. just listens for ``GET`` (and implicitly ``HEAD``).
  932. Starting with Flask 0.6, ``OPTIONS`` is implicitly
  933. added and handled by the standard request handling.
  934. """
  935. def decorator(f):
  936. endpoint = options.pop('endpoint', None)
  937. self.add_url_rule(rule, endpoint, f, **options)
  938. return f
  939. return decorator
  940. @setupmethod
  941. def endpoint(self, endpoint):
  942. """A decorator to register a function as an endpoint.
  943. Example::
  944. @app.endpoint('example.endpoint')
  945. def example():
  946. return "example"
  947. :param endpoint: the name of the endpoint
  948. """
  949. def decorator(f):
  950. self.view_functions[endpoint] = f
  951. return f
  952. return decorator
  953. @staticmethod
  954. def _get_exc_class_and_code(exc_class_or_code):
  955. """Ensure that we register only exceptions as handler keys"""
  956. if isinstance(exc_class_or_code, integer_types):
  957. exc_class = default_exceptions[exc_class_or_code]
  958. else:
  959. exc_class = exc_class_or_code
  960. assert issubclass(exc_class, Exception)
  961. if issubclass(exc_class, HTTPException):
  962. return exc_class, exc_class.code
  963. else:
  964. return exc_class, None
  965. @setupmethod
  966. def errorhandler(self, code_or_exception):
  967. """A decorator that is used to register a function give a given
  968. error code. Example::
  969. @app.errorhandler(404)
  970. def page_not_found(error):
  971. return 'This page does not exist', 404
  972. You can also register handlers for arbitrary exceptions::
  973. @app.errorhandler(DatabaseError)
  974. def special_exception_handler(error):
  975. return 'Database connection failed', 500
  976. You can also register a function as error handler without using
  977. the :meth:`errorhandler` decorator. The following example is
  978. equivalent to the one above::
  979. def page_not_found(error):
  980. return 'This page does not exist', 404
  981. app.error_handler_spec[None][404] = page_not_found
  982. Setting error handlers via assignments to :attr:`error_handler_spec`
  983. however is discouraged as it requires fiddling with nested dictionaries
  984. and the special case for arbitrary exception types.
  985. The first ``None`` refers to the active blueprint. If the error
  986. handler should be application wide ``None`` shall be used.
  987. .. versionadded:: 0.7
  988. Use :meth:`register_error_handler` instead of modifying
  989. :attr:`error_handler_spec` directly, for application wide error
  990. handlers.
  991. .. versionadded:: 0.7
  992. One can now additionally also register custom exception types
  993. that do not necessarily have to be a subclass of the
  994. :class:`~werkzeug.exceptions.HTTPException` class.
  995. :param code: the code as integer for the handler
  996. """
  997. def decorator(f):
  998. self._register_error_handler(None, code_or_exception, f)
  999. return f
  1000. return decorator
  1001. def register_error_handler(self, code_or_exception, f):
  1002. """Alternative error attach function to the :meth:`errorhandler`
  1003. decorator that is more straightforward to use for non decorator
  1004. usage.
  1005. .. versionadded:: 0.7
  1006. """
  1007. self._register_error_handler(None, code_or_exception, f)
  1008. @setupmethod
  1009. def _register_error_handler(self, key, code_or_exception, f):
  1010. """
  1011. :type key: None|str
  1012. :type code_or_exception: int|T<=Exception
  1013. :type f: callable
  1014. """
  1015. if isinstance(code_or_exception, HTTPException): # old broken behavior
  1016. raise ValueError(
  1017. 'Tried to register a handler for an exception instance {0!r}. '
  1018. 'Handlers can only be registered for exception classes or HTTP error codes.'
  1019. .format(code_or_exception))
  1020. exc_class, code = self._get_exc_class_and_code(code_or_exception)
  1021. handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})
  1022. handlers[exc_class] = f
  1023. @setupmethod
  1024. def template_filter(self, name=None):
  1025. """A decorator that is used to register custom template filter.
  1026. You can specify a name for the filter, otherwise the function
  1027. name will be used. Example::
  1028. @app.template_filter()
  1029. def reverse(s):
  1030. return s[::-1]
  1031. :param name: the optional name of the filter, otherwise the
  1032. function name will be used.
  1033. """
  1034. def decorator(f):
  1035. self.add_template_filter(f, name=name)
  1036. return f
  1037. return decorator
  1038. @setupmethod
  1039. def add_template_filter(self, f, name=None):
  1040. """Register a custom template filter. Works exactly like the
  1041. :meth:`template_filter` decorator.
  1042. :param name: the optional name of the filter, otherwise the
  1043. function name will be used.
  1044. """
  1045. self.jinja_env.filters[name or f.__name__] = f
  1046. @setupmethod
  1047. def template_test(self, name=None):
  1048. """A decorator that is used to register custom template test.
  1049. You can specify a name for the test, otherwise the function
  1050. name will be used. Example::
  1051. @app.template_test()
  1052. def is_prime(n):
  1053. if n == 2:
  1054. return True
  1055. for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
  1056. if n % i == 0:
  1057. return False
  1058. return True
  1059. .. versionadded:: 0.10
  1060. :param name: the optional name of the test, otherwise the
  1061. function name will be used.
  1062. """
  1063. def decorator(f):
  1064. self.add_template_test(f, name=name)
  1065. return f
  1066. return decorator
  1067. @setupmethod
  1068. def add_template_test(self, f, name=None):
  1069. """Register a custom template test. Works exactly like the
  1070. :meth:`template_test` decorator.
  1071. .. versionadded:: 0.10
  1072. :param name: the optional name of the test, otherwise the
  1073. function name will be used.
  1074. """
  1075. self.jinja_env.tests[name or f.__name__] = f
  1076. @setupmethod
  1077. def template_global(self, name=None):
  1078. """A decorator that is used to register a custom template global function.
  1079. You can specify a name for the global function, otherwise the function
  1080. name will be used. Example::
  1081. @app.template_global()
  1082. def double(n):
  1083. return 2 * n
  1084. .. versionadded:: 0.10
  1085. :param name: the optional name of the global function, otherwise the
  1086. function name will be used.
  1087. """
  1088. def decorator(f):
  1089. self.add_template_global(f, name=name)
  1090. return f
  1091. return decorator
  1092. @setupmethod
  1093. def add_template_global(self, f, name=None):
  1094. """Register a custom template global function. Works exactly like the
  1095. :meth:`template_global` decorator.
  1096. .. versionadded:: 0.10
  1097. :param name: the optional name of the global function, otherwise the
  1098. function name will be used.
  1099. """
  1100. self.jinja_env.globals[name or f.__name__] = f
  1101. @setupmethod
  1102. def before_request(self, f):
  1103. """Registers a function to run before each request.
  1104. The function will be called without any arguments.
  1105. If the function returns a non-None value, it's handled as
  1106. if it was the return value from the view and further
  1107. request handling is stopped.
  1108. """
  1109. self.before_request_funcs.setdefault(None, []).append(f)
  1110. return f
  1111. @setupmethod
  1112. def before_first_request(self, f):
  1113. """Registers a function to be run before the first request to this
  1114. instance of the application.
  1115. The function will be called without any arguments and its return
  1116. value is ignored.
  1117. .. versionadded:: 0.8
  1118. """
  1119. self.before_first_request_funcs.append(f)
  1120. return f
  1121. @setupmethod
  1122. def after_request(self, f):
  1123. """Register a function to be run after each request.
  1124. Your function must take one parameter, an instance of
  1125. :attr:`response_class` and return a new response object or the
  1126. same (see :meth:`process_response`).
  1127. As of Flask 0.7 this function might not be executed at the end of the
  1128. request in case an unhandled exception occurred.
  1129. """
  1130. self.after_request_funcs.setdefault(None, []).append(f)
  1131. return f
  1132. @setupmethod
  1133. def teardown_request(self, f):
  1134. """Register a function to be run at the end of each request,
  1135. regardless of whether there was an exception or not. These functions
  1136. are executed when the request context is popped, even if not an
  1137. actual request was performed.
  1138. Example::
  1139. ctx = app.test_request_context()
  1140. ctx.push()
  1141. ...
  1142. ctx.pop()
  1143. When ``ctx.pop()`` is executed in the above example, the teardown
  1144. functions are called just before the request context moves from the
  1145. stack of active contexts. This becomes relevant if you are using
  1146. such constructs in tests.
  1147. Generally teardown functions must take every necessary step to avoid
  1148. that they will fail. If they do execute code that might fail they
  1149. will have to surround the execution of these code by try/except
  1150. statements and log occurring errors.
  1151. When a teardown function was called because of a exception it will
  1152. be passed an error object.
  1153. The return values of teardown functions are ignored.
  1154. .. admonition:: Debug Note
  1155. In debug mode Flask will not tear down a request on an exception
  1156. immediately. Instead it will keep it alive so that the interactive
  1157. debugger can still access it. This behavior can be controlled
  1158. by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
  1159. """
  1160. self.teardown_request_funcs.setdefault(None, []).append(f)
  1161. return f
  1162. @setupmethod
  1163. def teardown_appcontext(self, f):
  1164. """Registers a function to be called when the application context
  1165. ends. These functions are typically also called when the request
  1166. context is popped.
  1167. Example::
  1168. ctx = app.app_context()
  1169. ctx.push()
  1170. ...
  1171. ctx.pop()
  1172. When ``ctx.pop()`` is executed in the above example, the teardown
  1173. functions are called just before the app context moves from the
  1174. stack of active contexts. This becomes relevant if you are using
  1175. such constructs in tests.
  1176. Since a request context typically also manages an application
  1177. context it would also be called when you pop a request context.
  1178. When a teardown function was called because of an exception it will
  1179. be passed an error object.
  1180. The return values of teardown functions are ignored.
  1181. .. versionadded:: 0.9
  1182. """
  1183. self.teardown_appcontext_funcs.append(f)
  1184. return f
  1185. @setupmethod
  1186. def context_processor(self, f):
  1187. """Registers a template context processor function."""
  1188. self.template_context_processors[None].append(f)
  1189. return f
  1190. @setupmethod
  1191. def shell_context_processor(self, f):
  1192. """Registers a shell context processor function.
  1193. .. versionadded:: 0.11
  1194. """
  1195. self.shell_context_processors.append(f)
  1196. return f
  1197. @setupmethod
  1198. def url_value_preprocessor(self, f):
  1199. """Registers a function as URL value preprocessor for all view
  1200. functions of the application. It's called before the view functions
  1201. are called and can modify the url values provided.
  1202. """
  1203. self.url_value_preprocessors.setdefault(None, []).append(f)
  1204. return f
  1205. @setupmethod
  1206. def url_defaults(self, f):
  1207. """Callback function for URL defaults for all view functions of the
  1208. application. It's called with the endpoint and values and should
  1209. update the values passed in place.
  1210. """
  1211. self.url_default_functions.setdefault(None, []).append(f)
  1212. return f
  1213. def _find_error_handler(self, e):
  1214. """Finds a registered error handler for the request’s blueprint.
  1215. Otherwise falls back to the app, returns None if not a suitable
  1216. handler is found.
  1217. """
  1218. exc_class, code = self._get_exc_class_and_code(type(e))
  1219. def find_handler(handler_map):
  1220. if not handler_map:
  1221. return
  1222. queue = deque(exc_class.__mro__)
  1223. # Protect from geniuses who might create circular references in
  1224. # __mro__
  1225. done = set()
  1226. while queue:
  1227. cls = queue.popleft()
  1228. if cls in done:
  1229. continue
  1230. done.add(cls)
  1231. handler = handler_map.get(cls)
  1232. if handler is not None:
  1233. # cache for next time exc_class is raised
  1234. handler_map[exc_class] = handler
  1235. return handler
  1236. queue.extend(cls.__mro__)
  1237. # try blueprint handlers
  1238. handler = find_handler(self.error_handler_spec
  1239. .get(request.blueprint, {})
  1240. .get(code))
  1241. if handler is not None:
  1242. return handler
  1243. # fall back to app handlers
  1244. return find_handler(self.error_handler_spec[None].get(code))
  1245. def handle_http_exception(self, e):
  1246. """Handles an HTTP exception. By default this will invoke the
  1247. registered error handlers and fall back to returning the
  1248. exception as response.
  1249. .. versionadded:: 0.3
  1250. """
  1251. # Proxy exceptions don't have error codes. We want to always return
  1252. # those unchanged as errors
  1253. if e.code is None:
  1254. return e
  1255. handler = self._find_error_handler(e)
  1256. if handler is None:
  1257. return e
  1258. return handler(e)
  1259. def trap_http_exception(self, e):
  1260. """Checks if an HTTP exception should be trapped or not. By default
  1261. this will return ``False`` for all exceptions except for a bad request
  1262. key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
  1263. also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
  1264. This is called for all HTTP exceptions raised by a view function.
  1265. If it returns ``True`` for any exception the error handler for this
  1266. exception is not called and it shows up as regular exception in the
  1267. traceback. This is helpful for debugging implicitly raised HTTP
  1268. exceptions.
  1269. .. versionadded:: 0.8
  1270. """
  1271. if self.config['TRAP_HTTP_EXCEPTIONS']:
  1272. return True
  1273. if self.config['TRAP_BAD_REQUEST_ERRORS']:
  1274. return isinstance(e, BadRequest)
  1275. return False
  1276. def handle_user_exception(self, e):
  1277. """This method is called whenever an exception occurs that should be
  1278. handled. A special case are
  1279. :class:`~werkzeug.exception.HTTPException`\s which are forwarded by
  1280. this function to the :meth:`handle_http_exception` method. This
  1281. function will either return a response value or reraise the
  1282. exception with the same traceback.
  1283. .. versionadded:: 0.7
  1284. """
  1285. exc_type, exc_value, tb = sys.exc_info()
  1286. assert exc_value is e
  1287. # ensure not to trash sys.exc_info() at that point in case someone
  1288. # wants the traceback preserved in handle_http_exception. Of course
  1289. # we cannot prevent users from trashing it themselves in a custom
  1290. # trap_http_exception method so that's their fault then.
  1291. if isinstance(e, HTTPException) and not self.trap_http_exception(e):
  1292. return self.handle_http_exception(e)
  1293. handler = self._find_error_handler(e)
  1294. if handler is None:
  1295. reraise(exc_type, exc_value, tb)
  1296. return handler(e)
  1297. def handle_exception(self, e):
  1298. """Default exception handling that kicks in when an exception
  1299. occurs that is not caught. In debug mode the exception will
  1300. be re-raised immediately, otherwise it is logged and the handler
  1301. for a 500 internal server error is used. If no such handler
  1302. exists, a default 500 internal server error message is displayed.
  1303. .. versionadded:: 0.3
  1304. """
  1305. exc_type, exc_value, tb = sys.exc_info()
  1306. got_request_exception.send(self, exception=e)
  1307. handler = self._find_error_handler(InternalServerError())
  1308. if self.propagate_exceptions:
  1309. # if we want to repropagate the exception, we can attempt to
  1310. # raise it with the whole traceback in case we can do that
  1311. # (the function was actually called from the except part)
  1312. # otherwise, we just raise the error again
  1313. if exc_value is e:
  1314. reraise(exc_type, exc_value, tb)
  1315. else:
  1316. raise e
  1317. self.log_exception((exc_type, exc_value, tb))
  1318. if handler is None:
  1319. return InternalServerError()
  1320. return handler(e)
  1321. def log_exception(self, exc_info):
  1322. """Logs an exception. This is called by :meth:`handle_exception`
  1323. if debugging is disabled and right before the handler is called.
  1324. The default implementation logs the exception as error on the
  1325. :attr:`logger`.
  1326. .. versionadded:: 0.8
  1327. """
  1328. self.logger.error('Exception on %s [%s]' % (
  1329. request.path,
  1330. request.method
  1331. ), exc_info=exc_info)
  1332. def raise_routing_exception(self, request):
  1333. """Exceptions that are recording during routing are reraised with
  1334. this method. During debug we are not reraising redirect requests
  1335. for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
  1336. a different error instead to help debug situations.
  1337. :internal:
  1338. """
  1339. if not self.debug \
  1340. or not isinstance(request.routing_exception, RequestRedirect) \
  1341. or request.method in ('GET', 'HEAD', 'OPTIONS'):
  1342. raise request.routing_exception
  1343. from .debughelpers import FormDataRoutingRedirect
  1344. raise FormDataRoutingRedirect(request)
  1345. def dispatch_request(self):
  1346. """Does the request dispatching. Matches the URL and returns the
  1347. return value of the view or error handler. This does not have to
  1348. be a response object. In order to convert the return value to a
  1349. proper response object, call :func:`make_response`.
  1350. .. versionchanged:: 0.7
  1351. This no longer does the exception handling, this code was
  1352. moved to the new :meth:`full_dispatch_request`.
  1353. """
  1354. req = _request_ctx_stack.top.request
  1355. if req.routing_exception is not None:
  1356. self.raise_routing_exception(req)
  1357. rule = req.url_rule
  1358. # if we provide automatic options for this URL and the
  1359. # request came with the OPTIONS method, reply automatically
  1360. if getattr(rule, 'provide_automatic_options', False) \
  1361. and req.method == 'OPTIONS':
  1362. return self.make_default_options_response()
  1363. # otherwise dispatch to the handler for that endpoint
  1364. return self.view_functions[rule.endpoint](**req.view_args)
  1365. def full_dispatch_request(self):
  1366. """Dispatches the request and on top of that performs request
  1367. pre and postprocessing as well as HTTP exception catching and
  1368. error handling.
  1369. .. versionadded:: 0.7
  1370. """
  1371. self.try_trigger_before_first_request_functions()
  1372. try:
  1373. request_started.send(self)
  1374. rv = self.preprocess_request()
  1375. if rv is None:
  1376. rv = self.dispatch_request()
  1377. except Exception as e:
  1378. rv = self.handle_user_exception(e)
  1379. response = self.make_response(rv)
  1380. response = self.process_response(response)
  1381. request_finished.send(self, response=response)
  1382. return response
  1383. def try_trigger_before_first_request_functions(self):
  1384. """Called before each request and will ensure that it triggers
  1385. the :attr:`before_first_request_funcs` and only exactly once per
  1386. application instance (which means process usually).
  1387. :internal:
  1388. """
  1389. if self._got_first_request:
  1390. return
  1391. with self._before_request_lock:
  1392. if self._got_first_request:
  1393. return
  1394. for func in self.before_first_request_funcs:
  1395. func()
  1396. self._got_first_request = True
  1397. def make_default_options_response(self):
  1398. """This method is called to create the default ``OPTIONS`` response.
  1399. This can be changed through subclassing to change the default
  1400. behavior of ``OPTIONS`` responses.
  1401. .. versionadded:: 0.7
  1402. """
  1403. adapter = _request_ctx_stack.top.url_adapter
  1404. if hasattr(adapter, 'allowed_methods'):
  1405. methods = adapter.allowed_methods()
  1406. else:
  1407. # fallback for Werkzeug < 0.7
  1408. methods = []
  1409. try:
  1410. adapter.match(method='--')
  1411. except MethodNotAllowed as e:
  1412. methods = e.valid_methods
  1413. except HTTPException as e:
  1414. pass
  1415. rv = self.response_class()
  1416. rv.allow.update(methods)
  1417. return rv
  1418. def should_ignore_error(self, error):
  1419. """This is called to figure out if an error should be ignored
  1420. or not as far as the teardown system is concerned. If this
  1421. function returns ``True`` then the teardown handlers will not be
  1422. passed the error.
  1423. .. versionadded:: 0.10
  1424. """
  1425. return False
  1426. def make_response(self, rv):
  1427. """Converts the return value from a view function to a real
  1428. response object that is an instance of :attr:`response_class`.
  1429. The following types are allowed for `rv`:
  1430. .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|
  1431. ======================= ===========================================
  1432. :attr:`response_class` the object is returned unchanged
  1433. :class:`str` a response object is created with the
  1434. string as body
  1435. :class:`unicode` a response object is created with the
  1436. string encoded to utf-8 as body
  1437. a WSGI function the function is called as WSGI application
  1438. and buffered as response object
  1439. :class:`tuple` A tuple in the form ``(response, status,
  1440. headers)`` or ``(response, headers)``
  1441. where `response` is any of the
  1442. types defined here, `status` is a string
  1443. or an integer and `headers` is a list or
  1444. a dictionary with header values.
  1445. ======================= ===========================================
  1446. :param rv: the return value from the view function
  1447. .. versionchanged:: 0.9
  1448. Previously a tuple was interpreted as the arguments for the
  1449. response object.
  1450. """
  1451. status_or_headers = headers = None
  1452. if isinstance(rv, tuple):
  1453. rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))
  1454. if rv is None:
  1455. raise ValueError('View function did not return a response')
  1456. if isinstance(status_or_headers, (dict, list)):
  1457. headers, status_or_headers = status_or_headers, None
  1458. if not isinstance(rv, self.response_class):
  1459. # When we create a response object directly, we let the constructor
  1460. # set the headers and status. We do this because there can be
  1461. # some extra logic involved when creating these objects with
  1462. # specific values (like default content type selection).
  1463. if isinstance(rv, (text_type, bytes, bytearray)):
  1464. rv = self.response_class(rv, headers=headers,
  1465. status=status_or_headers)
  1466. headers = status_or_headers = None
  1467. else:
  1468. rv = self.response_class.force_type(rv, request.environ)
  1469. if status_or_headers is not None:
  1470. if isinstance(status_or_headers, string_types):
  1471. rv.status = status_or_headers
  1472. else:
  1473. rv.status_code = status_or_headers
  1474. if headers:
  1475. rv.headers.extend(headers)
  1476. return rv
  1477. def create_url_adapter(self, request):
  1478. """Creates a URL adapter for the given request. The URL adapter
  1479. is created at a point where the request context is not yet set up
  1480. so the request is passed explicitly.
  1481. .. versionadded:: 0.6
  1482. .. versionchanged:: 0.9
  1483. This can now also be called without a request object when the
  1484. URL adapter is created for the application context.
  1485. """
  1486. if request is not None:
  1487. return self.url_map.bind_to_environ(request.environ,
  1488. server_name=self.config['SERVER_NAME'])
  1489. # We need at the very least the server name to be set for this
  1490. # to work.
  1491. if self.config['SERVER_NAME'] is not None:
  1492. return self.url_map.bind(
  1493. self.config['SERVER_NAME'],
  1494. script_name=self.config['APPLICATION_ROOT'] or '/',
  1495. url_scheme=self.config['PREFERRED_URL_SCHEME'])
  1496. def inject_url_defaults(self, endpoint, values):
  1497. """Injects the URL defaults for the given endpoint directly into
  1498. the values dictionary passed. This is used internally and
  1499. automatically called on URL building.
  1500. .. versionadded:: 0.7
  1501. """
  1502. funcs = self.url_default_functions.get(None, ())
  1503. if '.' in endpoint:
  1504. bp = endpoint.rsplit('.', 1)[0]
  1505. funcs = chain(funcs, self.url_default_functions.get(bp, ()))
  1506. for func in funcs:
  1507. func(endpoint, values)
  1508. def handle_url_build_error(self, error, endpoint, values):
  1509. """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.
  1510. """
  1511. exc_type, exc_value, tb = sys.exc_info()
  1512. for handler in self.url_build_error_handlers:
  1513. try:
  1514. rv = handler(error, endpoint, values)
  1515. if rv is not None:
  1516. return rv
  1517. except BuildError as e:
  1518. # make error available outside except block (py3)
  1519. error = e
  1520. # At this point we want to reraise the exception. If the error is
  1521. # still the same one we can reraise it with the original traceback,
  1522. # otherwise we raise it from here.
  1523. if error is exc_value:
  1524. reraise(exc_type, exc_value, tb)
  1525. raise error
  1526. def preprocess_request(self):
  1527. """Called before the actual request dispatching and will
  1528. call each :meth:`before_request` decorated function, passing no
  1529. arguments.
  1530. If any of these functions returns a value, it's handled as
  1531. if it was the return value from the view and further
  1532. request handling is stopped.
  1533. This also triggers the :meth:`url_value_processor` functions before
  1534. the actual :meth:`before_request` functions are called.
  1535. """
  1536. bp = _request_ctx_stack.top.request.blueprint
  1537. funcs = self.url_value_preprocessors.get(None, ())
  1538. if bp is not None and bp in self.url_value_preprocessors:
  1539. funcs = chain(funcs, self.url_value_preprocessors[bp])
  1540. for func in funcs:
  1541. func(request.endpoint, request.view_args)
  1542. funcs = self.before_request_funcs.get(None, ())
  1543. if bp is not None and bp in self.before_request_funcs:
  1544. funcs = chain(funcs, self.before_request_funcs[bp])
  1545. for func in funcs:
  1546. rv = func()
  1547. if rv is not None:
  1548. return rv
  1549. def process_response(self, response):
  1550. """Can be overridden in order to modify the response object
  1551. before it's sent to the WSGI server. By default this will
  1552. call all the :meth:`after_request` decorated functions.
  1553. .. versionchanged:: 0.5
  1554. As of Flask 0.5 the functions registered for after request
  1555. execution are called in reverse order of registration.
  1556. :param response: a :attr:`response_class` object.
  1557. :return: a new response object or the same, has to be an
  1558. instance of :attr:`response_class`.
  1559. """
  1560. ctx = _request_ctx_stack.top
  1561. bp = ctx.request.blueprint
  1562. funcs = ctx._after_request_functions
  1563. if bp is not None and bp in self.after_request_funcs:
  1564. funcs = chain(funcs, reversed(self.after_request_funcs[bp]))
  1565. if None in self.after_request_funcs:
  1566. funcs = chain(funcs, reversed(self.after_request_funcs[None]))
  1567. for handler in funcs:
  1568. response = handler(response)
  1569. if not self.session_interface.is_null_session(ctx.session):
  1570. self.save_session(ctx.session, response)
  1571. return response
  1572. def do_teardown_request(self, exc=_sentinel):
  1573. """Called after the actual request dispatching and will
  1574. call every as :meth:`teardown_request` decorated function. This is
  1575. not actually called by the :class:`Flask` object itself but is always
  1576. triggered when the request context is popped. That way we have a
  1577. tighter control over certain resources under testing environments.
  1578. .. versionchanged:: 0.9
  1579. Added the `exc` argument. Previously this was always using the
  1580. current exception information.
  1581. """
  1582. if exc is _sentinel:
  1583. exc = sys.exc_info()[1]
  1584. funcs = reversed(self.teardown_request_funcs.get(None, ()))
  1585. bp = _request_ctx_stack.top.request.blueprint
  1586. if bp is not None and bp in self.teardown_request_funcs:
  1587. funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))
  1588. for func in funcs:
  1589. func(exc)
  1590. request_tearing_down.send(self, exc=exc)
  1591. def do_teardown_appcontext(self, exc=_sentinel):
  1592. """Called when an application context is popped. This works pretty
  1593. much the same as :meth:`do_teardown_request` but for the application
  1594. context.
  1595. .. versionadded:: 0.9
  1596. """
  1597. if exc is _sentinel:
  1598. exc = sys.exc_info()[1]
  1599. for func in reversed(self.teardown_appcontext_funcs):
  1600. func(exc)
  1601. appcontext_tearing_down.send(self, exc=exc)
  1602. def app_context(self):
  1603. """Binds the application only. For as long as the application is bound
  1604. to the current context the :data:`flask.current_app` points to that
  1605. application. An application context is automatically created when a
  1606. request context is pushed if necessary.
  1607. Example usage::
  1608. with app.app_context():
  1609. ...
  1610. .. versionadded:: 0.9
  1611. """
  1612. return AppContext(self)
  1613. def request_context(self, environ):
  1614. """Creates a :class:`~flask.ctx.RequestContext` from the given
  1615. environment and binds it to the current context. This must be used in
  1616. combination with the ``with`` statement because the request is only bound
  1617. to the current context for the duration of the ``with`` block.
  1618. Example usage::
  1619. with app.request_context(environ):
  1620. do_something_with(request)
  1621. The object returned can also be used without the ``with`` statement
  1622. which is useful for working in the shell. The example above is
  1623. doing exactly the same as this code::
  1624. ctx = app.request_context(environ)
  1625. ctx.push()
  1626. try:
  1627. do_something_with(request)
  1628. finally:
  1629. ctx.pop()
  1630. .. versionchanged:: 0.3
  1631. Added support for non-with statement usage and ``with`` statement
  1632. is now passed the ctx object.
  1633. :param environ: a WSGI environment
  1634. """
  1635. return RequestContext(self, environ)
  1636. def test_request_context(self, *args, **kwargs):
  1637. """Creates a WSGI environment from the given values (see
  1638. :class:`werkzeug.test.EnvironBuilder` for more information, this
  1639. function accepts the same arguments).
  1640. """
  1641. from flask.testing import make_test_environ_builder
  1642. builder = make_test_environ_builder(self, *args, **kwargs)
  1643. try:
  1644. return self.request_context(builder.get_environ())
  1645. finally:
  1646. builder.close()
  1647. def wsgi_app(self, environ, start_response):
  1648. """The actual WSGI application. This is not implemented in
  1649. `__call__` so that middlewares can be applied without losing a
  1650. reference to the class. So instead of doing this::
  1651. app = MyMiddleware(app)
  1652. It's a better idea to do this instead::
  1653. app.wsgi_app = MyMiddleware(app.wsgi_app)
  1654. Then you still have the original application object around and
  1655. can continue to call methods on it.
  1656. .. versionchanged:: 0.7
  1657. The behavior of the before and after request callbacks was changed
  1658. under error conditions and a new callback was added that will
  1659. always execute at the end of the request, independent on if an
  1660. error occurred or not. See :ref:`callbacks-and-errors`.
  1661. :param environ: a WSGI environment
  1662. :param start_response: a callable accepting a status code,
  1663. a list of headers and an optional
  1664. exception context to start the response
  1665. """
  1666. ctx = self.request_context(environ)
  1667. ctx.push()
  1668. error = None
  1669. try:
  1670. try:
  1671. response = self.full_dispatch_request()
  1672. except Exception as e:
  1673. error = e
  1674. response = self.make_response(self.handle_exception(e))
  1675. return response(environ, start_response)
  1676. finally:
  1677. if self.should_ignore_error(error):
  1678. error = None
  1679. ctx.auto_pop(error)
  1680. def __call__(self, environ, start_response):
  1681. """Shortcut for :attr:`wsgi_app`."""
  1682. return self.wsgi_app(environ, start_response)
  1683. def __repr__(self):
  1684. return '<%s %r>' % (
  1685. self.__class__.__name__,
  1686. self.name,
  1687. )