app.py 75 KB

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