scaffold.py 34 KB

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