app.py 92 KB

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