app.py 96 KB

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