scaffold.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. import importlib.util
  2. import mimetypes
  3. import json
  4. import os
  5. import pathlib
  6. import pkgutil
  7. import sys
  8. import typing as t
  9. from collections import defaultdict
  10. from datetime import timedelta
  11. from functools import update_wrapper
  12. from jinja2 import ChoiceLoader, FileSystemLoader, ResourceLoader, PackageLoader
  13. from werkzeug.exceptions import default_exceptions
  14. from werkzeug.exceptions import HTTPException
  15. from . import typing as ft
  16. from .cli import AppGroup
  17. from .globals import current_app
  18. from .helpers import get_root_path
  19. from .helpers import locked_cached_property
  20. from .helpers import send_file
  21. from .helpers import send_from_directory
  22. from .templating import _default_template_ctx_processor
  23. if t.TYPE_CHECKING: # pragma: no cover
  24. from .wrappers import Response
  25. # a singleton sentinel value for parameter defaults
  26. _sentinel = object()
  27. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  28. T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)
  29. T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)
  30. T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)
  31. T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
  32. T_template_context_processor = t.TypeVar(
  33. "T_template_context_processor", bound=ft.TemplateContextProcessorCallable
  34. )
  35. T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)
  36. T_url_value_preprocessor = t.TypeVar(
  37. "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable
  38. )
  39. T_route = t.TypeVar("T_route", bound=ft.RouteCallable)
  40. def setupmethod(f: F) -> F:
  41. f_name = f.__name__
  42. def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
  43. self._check_setup_finished(f_name)
  44. return f(self, *args, **kwargs)
  45. return t.cast(F, update_wrapper(wrapper_func, f))
  46. class Scaffold:
  47. """Common behavior shared between :class:`~flask.Flask` and
  48. :class:`~flask.blueprints.Blueprint`.
  49. :param import_name: The import name of the module where this object
  50. is defined. Usually :attr:`__name__` should be used.
  51. :param static_folder: Path to a folder of static files to serve.
  52. If this is set, a static route will be added.
  53. :param static_url_path: URL prefix for the static route.
  54. :param template_folder: Path to a folder containing template files.
  55. for rendering. If this is set, a Jinja loader will be added.
  56. :param root_path: The path that static, template, and resource files
  57. are relative to. Typically not set, it is discovered based on
  58. the ``import_name``.
  59. .. versionadded:: 2.0
  60. """
  61. name: str
  62. _static_folder: t.Optional[str] = None
  63. _static_url_path: t.Optional[str] = None
  64. #: JSON encoder class used by :func:`flask.json.dumps`. If a
  65. #: blueprint sets this, it will be used instead of the app's value.
  66. #:
  67. #: .. deprecated:: 2.2
  68. #: Will be removed in Flask 2.3.
  69. json_encoder: t.Union[t.Type[json.JSONEncoder], None] = None
  70. #: JSON decoder class used by :func:`flask.json.loads`. If a
  71. #: blueprint sets this, it will be used instead of the app's value.
  72. #:
  73. #: .. deprecated:: 2.2
  74. #: Will be removed in Flask 2.3.
  75. json_decoder: t.Union[t.Type[json.JSONDecoder], None] = None
  76. def __init__(
  77. self,
  78. import_name: str,
  79. static_folder: t.Optional[t.Union[str, os.PathLike]] = None,
  80. static_url_path: t.Optional[str] = None,
  81. template_folder: t.Optional[t.Union[str, os.PathLike]] = None,
  82. root_path: t.Optional[str] = None,
  83. ):
  84. #: The name of the package or module that this object belongs
  85. #: to. Do not change this once it is set by the constructor.
  86. self.import_name = import_name
  87. self.static_folder = static_folder # type: ignore
  88. self.static_url_path = static_url_path
  89. package_name = import_name
  90. self.module_loader = pkgutil.find_loader(import_name)
  91. if self.module_loader and not self.module_loader.is_package(import_name):
  92. package_name = package_name.rsplit('.', 1)[0]
  93. self._builtin_resource_prefix = package_name.replace('.', '/')
  94. #: The path to the templates folder, relative to
  95. #: :attr:`root_path`, to add to the template loader. ``None`` if
  96. #: templates should not be added.
  97. self.template_folder = template_folder
  98. if root_path is None:
  99. root_path = get_root_path(self.import_name)
  100. #: Absolute path to the package on the filesystem. Used to look
  101. #: up resources contained in the package.
  102. self.root_path = root_path
  103. #: The Click command group for registering CLI commands for this
  104. #: object. The commands are available from the ``flask`` command
  105. #: once the application has been discovered and blueprints have
  106. #: been registered.
  107. self.cli = AppGroup()
  108. #: A dictionary mapping endpoint names to view functions.
  109. #:
  110. #: To register a view function, use the :meth:`route` decorator.
  111. #:
  112. #: This data structure is internal. It should not be modified
  113. #: directly and its format may change at any time.
  114. self.view_functions: t.Dict[str, t.Callable] = {}
  115. #: A data structure of registered error handlers, in the format
  116. #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is
  117. #: the name of a blueprint the handlers are active for, or
  118. #: ``None`` for all requests. The ``code`` key is the HTTP
  119. #: status code for ``HTTPException``, or ``None`` for
  120. #: other exceptions. The innermost dictionary maps exception
  121. #: classes to handler functions.
  122. #:
  123. #: To register an error handler, use the :meth:`errorhandler`
  124. #: decorator.
  125. #:
  126. #: This data structure is internal. It should not be modified
  127. #: directly and its format may change at any time.
  128. self.error_handler_spec: t.Dict[
  129. ft.AppOrBlueprintKey,
  130. t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ft.ErrorHandlerCallable]],
  131. ] = defaultdict(lambda: defaultdict(dict))
  132. #: A data structure of functions to call at the beginning of
  133. #: each request, in the format ``{scope: [functions]}``. The
  134. #: ``scope`` key is the name of a blueprint the functions are
  135. #: active for, or ``None`` for all requests.
  136. #:
  137. #: To register a function, use the :meth:`before_request`
  138. #: decorator.
  139. #:
  140. #: This data structure is internal. It should not be modified
  141. #: directly and its format may change at any time.
  142. self.before_request_funcs: t.Dict[
  143. ft.AppOrBlueprintKey, t.List[ft.BeforeRequestCallable]
  144. ] = defaultdict(list)
  145. #: A data structure of functions to call at the end of each
  146. #: request, in the format ``{scope: [functions]}``. The
  147. #: ``scope`` key is the name of a blueprint the functions are
  148. #: active for, or ``None`` for all requests.
  149. #:
  150. #: To register a function, use the :meth:`after_request`
  151. #: decorator.
  152. #:
  153. #: This data structure is internal. It should not be modified
  154. #: directly and its format may change at any time.
  155. self.after_request_funcs: t.Dict[
  156. ft.AppOrBlueprintKey, t.List[ft.AfterRequestCallable]
  157. ] = defaultdict(list)
  158. #: A data structure of functions to call at the end of each
  159. #: request even if an exception is raised, in the format
  160. #: ``{scope: [functions]}``. The ``scope`` key is the name of a
  161. #: blueprint the functions are active for, or ``None`` for all
  162. #: requests.
  163. #:
  164. #: To register a function, use the :meth:`teardown_request`
  165. #: decorator.
  166. #:
  167. #: This data structure is internal. It should not be modified
  168. #: directly and its format may change at any time.
  169. self.teardown_request_funcs: t.Dict[
  170. ft.AppOrBlueprintKey, t.List[ft.TeardownCallable]
  171. ] = defaultdict(list)
  172. #: A data structure of functions to call to pass extra context
  173. #: values when rendering templates, in the format
  174. #: ``{scope: [functions]}``. The ``scope`` key is the name of a
  175. #: blueprint the functions are active for, or ``None`` for all
  176. #: requests.
  177. #:
  178. #: To register a function, use the :meth:`context_processor`
  179. #: decorator.
  180. #:
  181. #: This data structure is internal. It should not be modified
  182. #: directly and its format may change at any time.
  183. self.template_context_processors: t.Dict[
  184. ft.AppOrBlueprintKey, t.List[ft.TemplateContextProcessorCallable]
  185. ] = defaultdict(list, {None: [_default_template_ctx_processor]})
  186. #: A data structure of functions to call to modify the keyword
  187. #: arguments passed to the view function, in the format
  188. #: ``{scope: [functions]}``. The ``scope`` key is the name of a
  189. #: blueprint the functions are active for, or ``None`` for all
  190. #: requests.
  191. #:
  192. #: To register a function, use the
  193. #: :meth:`url_value_preprocessor` decorator.
  194. #:
  195. #: This data structure is internal. It should not be modified
  196. #: directly and its format may change at any time.
  197. self.url_value_preprocessors: t.Dict[
  198. ft.AppOrBlueprintKey,
  199. t.List[ft.URLValuePreprocessorCallable],
  200. ] = defaultdict(list)
  201. #: A data structure of functions to call to modify the keyword
  202. #: arguments when generating URLs, in the format
  203. #: ``{scope: [functions]}``. The ``scope`` key is the name of a
  204. #: blueprint the functions are active for, or ``None`` for all
  205. #: requests.
  206. #:
  207. #: To register a function, use the :meth:`url_defaults`
  208. #: decorator.
  209. #:
  210. #: This data structure is internal. It should not be modified
  211. #: directly and its format may change at any time.
  212. self.url_default_functions: t.Dict[
  213. ft.AppOrBlueprintKey, t.List[ft.URLDefaultCallable]
  214. ] = defaultdict(list)
  215. def __repr__(self) -> str:
  216. return f"<{type(self).__name__} {self.name!r}>"
  217. def _check_setup_finished(self, f_name: str) -> None:
  218. raise NotImplementedError
  219. @property
  220. def static_folder(self) -> t.Optional[str]:
  221. """The absolute path to the configured static folder. ``None``
  222. if no static folder is set.
  223. """
  224. if self._static_folder is not None:
  225. return os.path.join(self.root_path, self._static_folder)
  226. else:
  227. return None
  228. @static_folder.setter
  229. def static_folder(self, value: t.Optional[t.Union[str, os.PathLike]]) -> None:
  230. if value is not None:
  231. value = os.fspath(value).rstrip(r"\/")
  232. self._static_folder = value
  233. @property
  234. def has_static_folder(self) -> bool:
  235. """``True`` if :attr:`static_folder` is set.
  236. .. versionadded:: 0.5
  237. """
  238. return self.static_folder is not None
  239. @property
  240. def static_url_path(self) -> t.Optional[str]:
  241. """The URL prefix that the static route will be accessible from.
  242. If it was not configured during init, it is derived from
  243. :attr:`static_folder`.
  244. """
  245. if self._static_url_path is not None:
  246. return self._static_url_path
  247. if self.static_folder is not None:
  248. basename = os.path.basename(self.static_folder)
  249. return f"/{basename}".rstrip("/")
  250. return None
  251. @static_url_path.setter
  252. def static_url_path(self, value: t.Optional[str]) -> None:
  253. if value is not None:
  254. value = value.rstrip("/")
  255. self._static_url_path = value
  256. def get_send_file_max_age(self, filename: t.Optional[str]) -> t.Optional[int]:
  257. """Used by :func:`send_file` to determine the ``max_age`` cache
  258. value for a given file path if it wasn't passed.
  259. By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
  260. the configuration of :data:`~flask.current_app`. This defaults
  261. to ``None``, which tells the browser to use conditional requests
  262. instead of a timed cache, which is usually preferable.
  263. .. versionchanged:: 2.0
  264. The default configuration is ``None`` instead of 12 hours.
  265. .. versionadded:: 0.9
  266. """
  267. value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
  268. if value is None:
  269. return None
  270. if isinstance(value, timedelta):
  271. return int(value.total_seconds())
  272. return value
  273. def send_static_file(self, filename: str) -> "Response":
  274. """The view function used to serve files from
  275. :attr:`static_folder`. A route is automatically registered for
  276. this view at :attr:`static_url_path` if :attr:`static_folder` is
  277. set.
  278. .. versionadded:: 0.5
  279. """
  280. if self.module_loader is not None:
  281. from io import BytesIO
  282. path = os.path.join(self._builtin_resource_prefix, self._static_folder, filename)
  283. try:
  284. data = self.module_loader.get_data(path)
  285. except IOError:
  286. data = None
  287. if data:
  288. mimetype = mimetypes.guess_type(filename)[0]
  289. max_age = self.get_send_file_max_age(filename)
  290. fobj = BytesIO(data)
  291. # Note: in case of uWSGI, might also need to set
  292. # `wsgi-disable-file-wrapper = true`
  293. # because, otherwise, uwsgi expects a `fileno` on it.
  294. return send_file(fobj, mimetype=mimetype, max_age=max_age, conditional=True)
  295. if not self.has_static_folder:
  296. raise RuntimeError("'static_folder' must be set to serve static_files.")
  297. # send_file only knows to call get_send_file_max_age on the app,
  298. # call it here so it works for blueprints too.
  299. max_age = self.get_send_file_max_age(filename)
  300. return send_from_directory(
  301. t.cast(str, self.static_folder), filename, max_age=max_age
  302. )
  303. @locked_cached_property
  304. def jinja_loader(self) -> t.Optional[FileSystemLoader]:
  305. """The Jinja loader for this object's templates. By default this
  306. is a class :class:`jinja2.loaders.FileSystemLoader` to
  307. :attr:`template_folder` if it is set.
  308. .. versionadded:: 0.5
  309. """
  310. if self.template_folder is not None:
  311. return ChoiceLoader([
  312. FileSystemLoader(os.path.join(self.root_path, self.template_folder)),
  313. PackageLoader(self.import_name, self.template_folder, skip_unknown_package=True),
  314. ResourceLoader(os.path.join(self._builtin_resource_prefix, self.template_folder), self.module_loader),
  315. ])
  316. else:
  317. return None
  318. def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
  319. """Open a resource file relative to :attr:`root_path` for
  320. reading.
  321. For example, if the file ``schema.sql`` is next to the file
  322. ``app.py`` where the ``Flask`` app is defined, it can be opened
  323. with:
  324. .. code-block:: python
  325. with app.open_resource("schema.sql") as f:
  326. conn.executescript(f.read())
  327. :param resource: Path to the resource relative to
  328. :attr:`root_path`.
  329. :param mode: Open the file in this mode. Only reading is
  330. supported, valid values are "r" (or "rt") and "rb".
  331. """
  332. if mode not in {"r", "rt", "rb"}:
  333. raise ValueError("Resources can only be opened for reading.")
  334. return open(os.path.join(self.root_path, resource), mode)
  335. def _method_route(
  336. self,
  337. method: str,
  338. rule: str,
  339. options: dict,
  340. ) -> t.Callable[[T_route], T_route]:
  341. if "methods" in options:
  342. raise TypeError("Use the 'route' decorator to use the 'methods' argument.")
  343. return self.route(rule, methods=[method], **options)
  344. @setupmethod
  345. def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
  346. """Shortcut for :meth:`route` with ``methods=["GET"]``.
  347. .. versionadded:: 2.0
  348. """
  349. return self._method_route("GET", rule, options)
  350. @setupmethod
  351. def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
  352. """Shortcut for :meth:`route` with ``methods=["POST"]``.
  353. .. versionadded:: 2.0
  354. """
  355. return self._method_route("POST", rule, options)
  356. @setupmethod
  357. def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
  358. """Shortcut for :meth:`route` with ``methods=["PUT"]``.
  359. .. versionadded:: 2.0
  360. """
  361. return self._method_route("PUT", rule, options)
  362. @setupmethod
  363. def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
  364. """Shortcut for :meth:`route` with ``methods=["DELETE"]``.
  365. .. versionadded:: 2.0
  366. """
  367. return self._method_route("DELETE", rule, options)
  368. @setupmethod
  369. def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
  370. """Shortcut for :meth:`route` with ``methods=["PATCH"]``.
  371. .. versionadded:: 2.0
  372. """
  373. return self._method_route("PATCH", rule, options)
  374. @setupmethod
  375. def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:
  376. """Decorate a view function to register it with the given URL
  377. rule and options. Calls :meth:`add_url_rule`, which has more
  378. details about the implementation.
  379. .. code-block:: python
  380. @app.route("/")
  381. def index():
  382. return "Hello, World!"
  383. See :ref:`url-route-registrations`.
  384. The endpoint name for the route defaults to the name of the view
  385. function if the ``endpoint`` parameter isn't passed.
  386. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
  387. ``OPTIONS`` are added automatically.
  388. :param rule: The URL rule string.
  389. :param options: Extra options passed to the
  390. :class:`~werkzeug.routing.Rule` object.
  391. """
  392. def decorator(f: T_route) -> T_route:
  393. endpoint = options.pop("endpoint", None)
  394. self.add_url_rule(rule, endpoint, f, **options)
  395. return f
  396. return decorator
  397. @setupmethod
  398. def add_url_rule(
  399. self,
  400. rule: str,
  401. endpoint: t.Optional[str] = None,
  402. view_func: t.Optional[ft.RouteCallable] = None,
  403. provide_automatic_options: t.Optional[bool] = None,
  404. **options: t.Any,
  405. ) -> None:
  406. """Register a rule for routing incoming requests and building
  407. URLs. The :meth:`route` decorator is a shortcut to call this
  408. with the ``view_func`` argument. These are equivalent:
  409. .. code-block:: python
  410. @app.route("/")
  411. def index():
  412. ...
  413. .. code-block:: python
  414. def index():
  415. ...
  416. app.add_url_rule("/", view_func=index)
  417. See :ref:`url-route-registrations`.
  418. The endpoint name for the route defaults to the name of the view
  419. function if the ``endpoint`` parameter isn't passed. An error
  420. will be raised if a function has already been registered for the
  421. endpoint.
  422. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is
  423. always added automatically, and ``OPTIONS`` is added
  424. automatically by default.
  425. ``view_func`` does not necessarily need to be passed, but if the
  426. rule should participate in routing an endpoint name must be
  427. associated with a view function at some point with the
  428. :meth:`endpoint` decorator.
  429. .. code-block:: python
  430. app.add_url_rule("/", endpoint="index")
  431. @app.endpoint("index")
  432. def index():
  433. ...
  434. If ``view_func`` has a ``required_methods`` attribute, those
  435. methods are added to the passed and automatic methods. If it
  436. has a ``provide_automatic_methods`` attribute, it is used as the
  437. default if the parameter is not passed.
  438. :param rule: The URL rule string.
  439. :param endpoint: The endpoint name to associate with the rule
  440. and view function. Used when routing and building URLs.
  441. Defaults to ``view_func.__name__``.
  442. :param view_func: The view function to associate with the
  443. endpoint name.
  444. :param provide_automatic_options: Add the ``OPTIONS`` method and
  445. respond to ``OPTIONS`` requests automatically.
  446. :param options: Extra options passed to the
  447. :class:`~werkzeug.routing.Rule` object.
  448. """
  449. raise NotImplementedError
  450. @setupmethod
  451. def endpoint(self, endpoint: str) -> t.Callable[[F], F]:
  452. """Decorate a view function to register it for the given
  453. endpoint. Used if a rule is added without a ``view_func`` with
  454. :meth:`add_url_rule`.
  455. .. code-block:: python
  456. app.add_url_rule("/ex", endpoint="example")
  457. @app.endpoint("example")
  458. def example():
  459. ...
  460. :param endpoint: The endpoint name to associate with the view
  461. function.
  462. """
  463. def decorator(f: F) -> F:
  464. self.view_functions[endpoint] = f
  465. return f
  466. return decorator
  467. @setupmethod
  468. def before_request(self, f: T_before_request) -> T_before_request:
  469. """Register a function to run before each request.
  470. For example, this can be used to open a database connection, or
  471. to load the logged in user from the session.
  472. .. code-block:: python
  473. @app.before_request
  474. def load_user():
  475. if "user_id" in session:
  476. g.user = db.session.get(session["user_id"])
  477. The function will be called without any arguments. If it returns
  478. a non-``None`` value, the value is handled as if it was the
  479. return value from the view, and further request handling is
  480. stopped.
  481. This is available on both app and blueprint objects. When used on an app, this
  482. executes before every request. When used on a blueprint, this executes before
  483. every request that the blueprint handles. To register with a blueprint and
  484. execute before every request, use :meth:`.Blueprint.before_app_request`.
  485. """
  486. self.before_request_funcs.setdefault(None, []).append(f)
  487. return f
  488. @setupmethod
  489. def after_request(self, f: T_after_request) -> T_after_request:
  490. """Register a function to run after each request to this object.
  491. The function is called with the response object, and must return
  492. a response object. This allows the functions to modify or
  493. replace the response before it is sent.
  494. If a function raises an exception, any remaining
  495. ``after_request`` functions will not be called. Therefore, this
  496. should not be used for actions that must execute, such as to
  497. close resources. Use :meth:`teardown_request` for that.
  498. This is available on both app and blueprint objects. When used on an app, this
  499. executes after every request. When used on a blueprint, this executes after
  500. every request that the blueprint handles. To register with a blueprint and
  501. execute after every request, use :meth:`.Blueprint.after_app_request`.
  502. """
  503. self.after_request_funcs.setdefault(None, []).append(f)
  504. return f
  505. @setupmethod
  506. def teardown_request(self, f: T_teardown) -> T_teardown:
  507. """Register a function to be called when the request context is
  508. popped. Typically this happens at the end of each request, but
  509. contexts may be pushed manually as well during testing.
  510. .. code-block:: python
  511. with app.test_request_context():
  512. ...
  513. When the ``with`` block exits (or ``ctx.pop()`` is called), the
  514. teardown functions are called just before the request context is
  515. made inactive.
  516. When a teardown function was called because of an unhandled
  517. exception it will be passed an error object. If an
  518. :meth:`errorhandler` is registered, it will handle the exception
  519. and the teardown will not receive it.
  520. Teardown functions must avoid raising exceptions. If they
  521. execute code that might fail they must surround that code with a
  522. ``try``/``except`` block and log any errors.
  523. The return values of teardown functions are ignored.
  524. This is available on both app and blueprint objects. When used on an app, this
  525. executes after every request. When used on a blueprint, this executes after
  526. every request that the blueprint handles. To register with a blueprint and
  527. execute after every request, use :meth:`.Blueprint.teardown_app_request`.
  528. """
  529. self.teardown_request_funcs.setdefault(None, []).append(f)
  530. return f
  531. @setupmethod
  532. def context_processor(
  533. self,
  534. f: T_template_context_processor,
  535. ) -> T_template_context_processor:
  536. """Registers a template context processor function. These functions run before
  537. rendering a template. The keys of the returned dict are added as variables
  538. available in the template.
  539. This is available on both app and blueprint objects. When used on an app, this
  540. is called for every rendered template. When used on a blueprint, this is called
  541. for templates rendered from the blueprint's views. To register with a blueprint
  542. and affect every template, use :meth:`.Blueprint.app_context_processor`.
  543. """
  544. self.template_context_processors[None].append(f)
  545. return f
  546. @setupmethod
  547. def url_value_preprocessor(
  548. self,
  549. f: T_url_value_preprocessor,
  550. ) -> T_url_value_preprocessor:
  551. """Register a URL value preprocessor function for all view
  552. functions in the application. These functions will be called before the
  553. :meth:`before_request` functions.
  554. The function can modify the values captured from the matched url before
  555. they are passed to the view. For example, this can be used to pop a
  556. common language code value and place it in ``g`` rather than pass it to
  557. every view.
  558. The function is passed the endpoint name and values dict. The return
  559. value is ignored.
  560. This is available on both app and blueprint objects. When used on an app, this
  561. is called for every request. When used on a blueprint, this is called for
  562. requests that the blueprint handles. To register with a blueprint and affect
  563. every request, use :meth:`.Blueprint.app_url_value_preprocessor`.
  564. """
  565. self.url_value_preprocessors[None].append(f)
  566. return f
  567. @setupmethod
  568. def url_defaults(self, f: T_url_defaults) -> T_url_defaults:
  569. """Callback function for URL defaults for all view functions of the
  570. application. It's called with the endpoint and values and should
  571. update the values passed in place.
  572. This is available on both app and blueprint objects. When used on an app, this
  573. is called for every request. When used on a blueprint, this is called for
  574. requests that the blueprint handles. To register with a blueprint and affect
  575. every request, use :meth:`.Blueprint.app_url_defaults`.
  576. """
  577. self.url_default_functions[None].append(f)
  578. return f
  579. @setupmethod
  580. def errorhandler(
  581. self, code_or_exception: t.Union[t.Type[Exception], int]
  582. ) -> t.Callable[[T_error_handler], T_error_handler]:
  583. """Register a function to handle errors by code or exception class.
  584. A decorator that is used to register a function given an
  585. error code. Example::
  586. @app.errorhandler(404)
  587. def page_not_found(error):
  588. return 'This page does not exist', 404
  589. You can also register handlers for arbitrary exceptions::
  590. @app.errorhandler(DatabaseError)
  591. def special_exception_handler(error):
  592. return 'Database connection failed', 500
  593. This is available on both app and blueprint objects. When used on an app, this
  594. can handle errors from every request. When used on a blueprint, this can handle
  595. errors from requests that the blueprint handles. To register with a blueprint
  596. and affect every request, use :meth:`.Blueprint.app_errorhandler`.
  597. .. versionadded:: 0.7
  598. Use :meth:`register_error_handler` instead of modifying
  599. :attr:`error_handler_spec` directly, for application wide error
  600. handlers.
  601. .. versionadded:: 0.7
  602. One can now additionally also register custom exception types
  603. that do not necessarily have to be a subclass of the
  604. :class:`~werkzeug.exceptions.HTTPException` class.
  605. :param code_or_exception: the code as integer for the handler, or
  606. an arbitrary exception
  607. """
  608. def decorator(f: T_error_handler) -> T_error_handler:
  609. self.register_error_handler(code_or_exception, f)
  610. return f
  611. return decorator
  612. @setupmethod
  613. def register_error_handler(
  614. self,
  615. code_or_exception: t.Union[t.Type[Exception], int],
  616. f: ft.ErrorHandlerCallable,
  617. ) -> None:
  618. """Alternative error attach function to the :meth:`errorhandler`
  619. decorator that is more straightforward to use for non decorator
  620. usage.
  621. .. versionadded:: 0.7
  622. """
  623. exc_class, code = self._get_exc_class_and_code(code_or_exception)
  624. self.error_handler_spec[None][code][exc_class] = f
  625. @staticmethod
  626. def _get_exc_class_and_code(
  627. exc_class_or_code: t.Union[t.Type[Exception], int]
  628. ) -> t.Tuple[t.Type[Exception], t.Optional[int]]:
  629. """Get the exception class being handled. For HTTP status codes
  630. or ``HTTPException`` subclasses, return both the exception and
  631. status code.
  632. :param exc_class_or_code: Any exception class, or an HTTP status
  633. code as an integer.
  634. """
  635. exc_class: t.Type[Exception]
  636. if isinstance(exc_class_or_code, int):
  637. try:
  638. exc_class = default_exceptions[exc_class_or_code]
  639. except KeyError:
  640. raise ValueError(
  641. f"'{exc_class_or_code}' is not a recognized HTTP"
  642. " error code. Use a subclass of HTTPException with"
  643. " that code instead."
  644. ) from None
  645. else:
  646. exc_class = exc_class_or_code
  647. if isinstance(exc_class, Exception):
  648. raise TypeError(
  649. f"{exc_class!r} is an instance, not a class. Handlers"
  650. " can only be registered for Exception classes or HTTP"
  651. " error codes."
  652. )
  653. if not issubclass(exc_class, Exception):
  654. raise ValueError(
  655. f"'{exc_class.__name__}' is not a subclass of Exception."
  656. " Handlers can only be registered for Exception classes"
  657. " or HTTP error codes."
  658. )
  659. if issubclass(exc_class, HTTPException):
  660. return exc_class, exc_class.code
  661. else:
  662. return exc_class, None
  663. def _endpoint_from_view_func(view_func: t.Callable) -> str:
  664. """Internal helper that returns the default endpoint for a given
  665. function. This always is the function name.
  666. """
  667. assert view_func is not None, "expected view func if endpoint is not provided."
  668. return view_func.__name__
  669. def _matching_loader_thinks_module_is_package(loader, mod_name):
  670. """Attempt to figure out if the given name is a package or a module.
  671. :param: loader: The loader that handled the name.
  672. :param mod_name: The name of the package or module.
  673. """
  674. # Use loader.is_package if it's available.
  675. if hasattr(loader, "is_package"):
  676. return loader.is_package(mod_name)
  677. cls = type(loader)
  678. # NamespaceLoader doesn't implement is_package, but all names it
  679. # loads must be packages.
  680. if cls.__module__ == "_frozen_importlib" and cls.__name__ == "NamespaceLoader":
  681. return True
  682. # Otherwise we need to fail with an error that explains what went
  683. # wrong.
  684. raise AttributeError(
  685. f"'{cls.__name__}.is_package()' must be implemented for PEP 302"
  686. f" import hooks."
  687. )
  688. def _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool:
  689. # Path.is_relative_to doesn't exist until Python 3.9
  690. try:
  691. path.relative_to(base)
  692. return True
  693. except ValueError:
  694. return False
  695. def _find_package_path(import_name):
  696. """Find the path that contains the package or module."""
  697. root_mod_name, _, _ = import_name.partition(".")
  698. try:
  699. root_spec = importlib.util.find_spec(root_mod_name)
  700. if root_spec is None:
  701. raise ValueError("not found")
  702. # ImportError: the machinery told us it does not exist
  703. # ValueError:
  704. # - the module name was invalid
  705. # - the module name is __main__
  706. # - *we* raised `ValueError` due to `root_spec` being `None`
  707. except (ImportError, ValueError):
  708. pass # handled below
  709. else:
  710. # namespace package
  711. if root_spec.origin in {"namespace", None}:
  712. package_spec = importlib.util.find_spec(import_name)
  713. if package_spec is not None and package_spec.submodule_search_locations:
  714. # Pick the path in the namespace that contains the submodule.
  715. package_path = pathlib.Path(
  716. os.path.commonpath(package_spec.submodule_search_locations)
  717. )
  718. search_locations = (
  719. location
  720. for location in root_spec.submodule_search_locations
  721. if _path_is_relative_to(package_path, location)
  722. )
  723. else:
  724. # Pick the first path.
  725. search_locations = iter(root_spec.submodule_search_locations)
  726. return os.path.dirname(next(search_locations))
  727. # a package (with __init__.py)
  728. elif root_spec.submodule_search_locations:
  729. return os.path.dirname(os.path.dirname(root_spec.origin))
  730. # just a normal module
  731. else:
  732. return os.path.dirname(root_spec.origin)
  733. # we were unable to find the `package_path` using PEP 451 loaders
  734. loader = pkgutil.get_loader(root_mod_name)
  735. if loader is None or root_mod_name == "__main__":
  736. # import name is not found, or interactive/main module
  737. return os.getcwd()
  738. if hasattr(loader, "get_filename"):
  739. filename = loader.get_filename(root_mod_name)
  740. elif hasattr(loader, "archive"):
  741. # zipimporter's loader.archive points to the .egg or .zip file.
  742. filename = loader.archive
  743. else:
  744. # At least one loader is missing both get_filename and archive:
  745. # Google App Engine's HardenedModulesHook, use __file__.
  746. filename = importlib.import_module(root_mod_name).__file__
  747. package_path = os.path.abspath(os.path.dirname(filename))
  748. # If the imported name is a package, filename is currently pointing
  749. # to the root of the package, need to get the current directory.
  750. if _matching_loader_thinks_module_is_package(loader, root_mod_name):
  751. package_path = os.path.dirname(package_path)
  752. return package_path
  753. def find_package(import_name: str):
  754. """Find the prefix that a package is installed under, and the path
  755. that it would be imported from.
  756. The prefix is the directory containing the standard directory
  757. hierarchy (lib, bin, etc.). If the package is not installed to the
  758. system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),
  759. ``None`` is returned.
  760. The path is the entry in :attr:`sys.path` that contains the package
  761. for import. If the package is not installed, it's assumed that the
  762. package was imported from the current working directory.
  763. """
  764. package_path = _find_package_path(import_name)
  765. py_prefix = os.path.abspath(sys.prefix)
  766. # installed to the system
  767. if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):
  768. return py_prefix, package_path
  769. site_parent, site_folder = os.path.split(package_path)
  770. # installed to a virtualenv
  771. if site_folder.lower() == "site-packages":
  772. parent, folder = os.path.split(site_parent)
  773. # Windows (prefix/lib/site-packages)
  774. if folder.lower() == "lib":
  775. return parent, package_path
  776. # Unix (prefix/lib/pythonX.Y/site-packages)
  777. if os.path.basename(parent).lower() == "lib":
  778. return os.path.dirname(parent), package_path
  779. # something else (prefix/site-packages)
  780. return site_parent, package_path
  781. # not installed
  782. return None, package_path