scaffold.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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, 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:
  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. PackageLoader(self.import_name, self.template_folder, skip_unknown_package=True),
  306. ResourceLoader(os.path.join(self._builtin_resource_prefix, self.template_folder), self.module_loader),
  307. ])
  308. else:
  309. return None
  310. def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
  311. """Open a resource file relative to :attr:`root_path` for
  312. reading.
  313. For example, if the file ``schema.sql`` is next to the file
  314. ``app.py`` where the ``Flask`` app is defined, it can be opened
  315. with:
  316. .. code-block:: python
  317. with app.open_resource("schema.sql") as f:
  318. conn.executescript(f.read())
  319. :param resource: Path to the resource relative to
  320. :attr:`root_path`.
  321. :param mode: Open the file in this mode. Only reading is
  322. supported, valid values are "r" (or "rt") and "rb".
  323. """
  324. if mode not in {"r", "rt", "rb"}:
  325. raise ValueError("Resources can only be opened for reading.")
  326. return open(os.path.join(self.root_path, resource), mode)
  327. def _method_route(
  328. self,
  329. method: str,
  330. rule: str,
  331. options: dict,
  332. ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:
  333. if "methods" in options:
  334. raise TypeError("Use the 'route' decorator to use the 'methods' argument.")
  335. return self.route(rule, methods=[method], **options)
  336. def get(
  337. self, rule: str, **options: t.Any
  338. ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:
  339. """Shortcut for :meth:`route` with ``methods=["GET"]``.
  340. .. versionadded:: 2.0
  341. """
  342. return self._method_route("GET", rule, options)
  343. def post(
  344. self, rule: str, **options: t.Any
  345. ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:
  346. """Shortcut for :meth:`route` with ``methods=["POST"]``.
  347. .. versionadded:: 2.0
  348. """
  349. return self._method_route("POST", rule, options)
  350. def put(
  351. self, rule: str, **options: t.Any
  352. ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:
  353. """Shortcut for :meth:`route` with ``methods=["PUT"]``.
  354. .. versionadded:: 2.0
  355. """
  356. return self._method_route("PUT", rule, options)
  357. def delete(
  358. self, rule: str, **options: t.Any
  359. ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:
  360. """Shortcut for :meth:`route` with ``methods=["DELETE"]``.
  361. .. versionadded:: 2.0
  362. """
  363. return self._method_route("DELETE", rule, options)
  364. def patch(
  365. self, rule: str, **options: t.Any
  366. ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:
  367. """Shortcut for :meth:`route` with ``methods=["PATCH"]``.
  368. .. versionadded:: 2.0
  369. """
  370. return self._method_route("PATCH", rule, options)
  371. def route(
  372. self, rule: str, **options: t.Any
  373. ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:
  374. """Decorate a view function to register it with the given URL
  375. rule and options. Calls :meth:`add_url_rule`, which has more
  376. details about the implementation.
  377. .. code-block:: python
  378. @app.route("/")
  379. def index():
  380. return "Hello, World!"
  381. See :ref:`url-route-registrations`.
  382. The endpoint name for the route defaults to the name of the view
  383. function if the ``endpoint`` parameter isn't passed.
  384. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
  385. ``OPTIONS`` are added automatically.
  386. :param rule: The URL rule string.
  387. :param options: Extra options passed to the
  388. :class:`~werkzeug.routing.Rule` object.
  389. """
  390. def decorator(f: ft.RouteDecorator) -> ft.RouteDecorator:
  391. endpoint = options.pop("endpoint", None)
  392. self.add_url_rule(rule, endpoint, f, **options)
  393. return f
  394. return decorator
  395. @setupmethod
  396. def add_url_rule(
  397. self,
  398. rule: str,
  399. endpoint: t.Optional[str] = None,
  400. view_func: t.Optional[ft.ViewCallable] = None,
  401. provide_automatic_options: t.Optional[bool] = None,
  402. **options: t.Any,
  403. ) -> None:
  404. """Register a rule for routing incoming requests and building
  405. URLs. The :meth:`route` decorator is a shortcut to call this
  406. with the ``view_func`` argument. These are equivalent:
  407. .. code-block:: python
  408. @app.route("/")
  409. def index():
  410. ...
  411. .. code-block:: python
  412. def index():
  413. ...
  414. app.add_url_rule("/", view_func=index)
  415. See :ref:`url-route-registrations`.
  416. The endpoint name for the route defaults to the name of the view
  417. function if the ``endpoint`` parameter isn't passed. An error
  418. will be raised if a function has already been registered for the
  419. endpoint.
  420. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is
  421. always added automatically, and ``OPTIONS`` is added
  422. automatically by default.
  423. ``view_func`` does not necessarily need to be passed, but if the
  424. rule should participate in routing an endpoint name must be
  425. associated with a view function at some point with the
  426. :meth:`endpoint` decorator.
  427. .. code-block:: python
  428. app.add_url_rule("/", endpoint="index")
  429. @app.endpoint("index")
  430. def index():
  431. ...
  432. If ``view_func`` has a ``required_methods`` attribute, those
  433. methods are added to the passed and automatic methods. If it
  434. has a ``provide_automatic_methods`` attribute, it is used as the
  435. default if the parameter is not passed.
  436. :param rule: The URL rule string.
  437. :param endpoint: The endpoint name to associate with the rule
  438. and view function. Used when routing and building URLs.
  439. Defaults to ``view_func.__name__``.
  440. :param view_func: The view function to associate with the
  441. endpoint name.
  442. :param provide_automatic_options: Add the ``OPTIONS`` method and
  443. respond to ``OPTIONS`` requests automatically.
  444. :param options: Extra options passed to the
  445. :class:`~werkzeug.routing.Rule` object.
  446. """
  447. raise NotImplementedError
  448. def endpoint(self, endpoint: str) -> t.Callable:
  449. """Decorate a view function to register it for the given
  450. endpoint. Used if a rule is added without a ``view_func`` with
  451. :meth:`add_url_rule`.
  452. .. code-block:: python
  453. app.add_url_rule("/ex", endpoint="example")
  454. @app.endpoint("example")
  455. def example():
  456. ...
  457. :param endpoint: The endpoint name to associate with the view
  458. function.
  459. """
  460. def decorator(f):
  461. self.view_functions[endpoint] = f
  462. return f
  463. return decorator
  464. @setupmethod
  465. def before_request(self, f: ft.BeforeRequestCallable) -> ft.BeforeRequestCallable:
  466. """Register a function to run before each request.
  467. For example, this can be used to open a database connection, or
  468. to load the logged in user from the session.
  469. .. code-block:: python
  470. @app.before_request
  471. def load_user():
  472. if "user_id" in session:
  473. g.user = db.session.get(session["user_id"])
  474. The function will be called without any arguments. If it returns
  475. a non-``None`` value, the value is handled as if it was the
  476. return value from the view, and further request handling is
  477. stopped.
  478. """
  479. self.before_request_funcs.setdefault(None, []).append(f)
  480. return f
  481. @setupmethod
  482. def after_request(self, f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:
  483. """Register a function to run after each request to this object.
  484. The function is called with the response object, and must return
  485. a response object. This allows the functions to modify or
  486. replace the response before it is sent.
  487. If a function raises an exception, any remaining
  488. ``after_request`` functions will not be called. Therefore, this
  489. should not be used for actions that must execute, such as to
  490. close resources. Use :meth:`teardown_request` for that.
  491. """
  492. self.after_request_funcs.setdefault(None, []).append(f)
  493. return f
  494. @setupmethod
  495. def teardown_request(self, f: ft.TeardownCallable) -> ft.TeardownCallable:
  496. """Register a function to be run at the end of each request,
  497. regardless of whether there was an exception or not. These functions
  498. are executed when the request context is popped, even if not an
  499. actual request was performed.
  500. Example::
  501. ctx = app.test_request_context()
  502. ctx.push()
  503. ...
  504. ctx.pop()
  505. When ``ctx.pop()`` is executed in the above example, the teardown
  506. functions are called just before the request context moves from the
  507. stack of active contexts. This becomes relevant if you are using
  508. such constructs in tests.
  509. Teardown functions must avoid raising exceptions. If
  510. they execute code that might fail they
  511. will have to surround the execution of that code with try/except
  512. statements and log any errors.
  513. When a teardown function was called because of an exception it will
  514. be passed an error object.
  515. The return values of teardown functions are ignored.
  516. .. admonition:: Debug Note
  517. In debug mode Flask will not tear down a request on an exception
  518. immediately. Instead it will keep it alive so that the interactive
  519. debugger can still access it. This behavior can be controlled
  520. by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
  521. """
  522. self.teardown_request_funcs.setdefault(None, []).append(f)
  523. return f
  524. @setupmethod
  525. def context_processor(
  526. self, f: ft.TemplateContextProcessorCallable
  527. ) -> ft.TemplateContextProcessorCallable:
  528. """Registers a template context processor function."""
  529. self.template_context_processors[None].append(f)
  530. return f
  531. @setupmethod
  532. def url_value_preprocessor(
  533. self, f: ft.URLValuePreprocessorCallable
  534. ) -> ft.URLValuePreprocessorCallable:
  535. """Register a URL value preprocessor function for all view
  536. functions in the application. These functions will be called before the
  537. :meth:`before_request` functions.
  538. The function can modify the values captured from the matched url before
  539. they are passed to the view. For example, this can be used to pop a
  540. common language code value and place it in ``g`` rather than pass it to
  541. every view.
  542. The function is passed the endpoint name and values dict. The return
  543. value is ignored.
  544. """
  545. self.url_value_preprocessors[None].append(f)
  546. return f
  547. @setupmethod
  548. def url_defaults(self, f: ft.URLDefaultCallable) -> ft.URLDefaultCallable:
  549. """Callback function for URL defaults for all view functions of the
  550. application. It's called with the endpoint and values and should
  551. update the values passed in place.
  552. """
  553. self.url_default_functions[None].append(f)
  554. return f
  555. @setupmethod
  556. def errorhandler(
  557. self, code_or_exception: t.Union[t.Type[Exception], int]
  558. ) -> t.Callable[[ft.ErrorHandlerDecorator], ft.ErrorHandlerDecorator]:
  559. """Register a function to handle errors by code or exception class.
  560. A decorator that is used to register a function given an
  561. error code. Example::
  562. @app.errorhandler(404)
  563. def page_not_found(error):
  564. return 'This page does not exist', 404
  565. You can also register handlers for arbitrary exceptions::
  566. @app.errorhandler(DatabaseError)
  567. def special_exception_handler(error):
  568. return 'Database connection failed', 500
  569. .. versionadded:: 0.7
  570. Use :meth:`register_error_handler` instead of modifying
  571. :attr:`error_handler_spec` directly, for application wide error
  572. handlers.
  573. .. versionadded:: 0.7
  574. One can now additionally also register custom exception types
  575. that do not necessarily have to be a subclass of the
  576. :class:`~werkzeug.exceptions.HTTPException` class.
  577. :param code_or_exception: the code as integer for the handler, or
  578. an arbitrary exception
  579. """
  580. def decorator(f: ft.ErrorHandlerDecorator) -> ft.ErrorHandlerDecorator:
  581. self.register_error_handler(code_or_exception, f)
  582. return f
  583. return decorator
  584. @setupmethod
  585. def register_error_handler(
  586. self,
  587. code_or_exception: t.Union[t.Type[Exception], int],
  588. f: ft.ErrorHandlerCallable,
  589. ) -> None:
  590. """Alternative error attach function to the :meth:`errorhandler`
  591. decorator that is more straightforward to use for non decorator
  592. usage.
  593. .. versionadded:: 0.7
  594. """
  595. if isinstance(code_or_exception, HTTPException): # old broken behavior
  596. raise ValueError(
  597. "Tried to register a handler for an exception instance"
  598. f" {code_or_exception!r}. Handlers can only be"
  599. " registered for exception classes or HTTP error codes."
  600. )
  601. try:
  602. exc_class, code = self._get_exc_class_and_code(code_or_exception)
  603. except KeyError:
  604. raise KeyError(
  605. f"'{code_or_exception}' is not a recognized HTTP error"
  606. " code. Use a subclass of HTTPException with that code"
  607. " instead."
  608. ) from None
  609. self.error_handler_spec[None][code][exc_class] = f
  610. @staticmethod
  611. def _get_exc_class_and_code(
  612. exc_class_or_code: t.Union[t.Type[Exception], int]
  613. ) -> t.Tuple[t.Type[Exception], t.Optional[int]]:
  614. """Get the exception class being handled. For HTTP status codes
  615. or ``HTTPException`` subclasses, return both the exception and
  616. status code.
  617. :param exc_class_or_code: Any exception class, or an HTTP status
  618. code as an integer.
  619. """
  620. exc_class: t.Type[Exception]
  621. if isinstance(exc_class_or_code, int):
  622. exc_class = default_exceptions[exc_class_or_code]
  623. else:
  624. exc_class = exc_class_or_code
  625. assert issubclass(
  626. exc_class, Exception
  627. ), "Custom exceptions must be subclasses of Exception."
  628. if issubclass(exc_class, HTTPException):
  629. return exc_class, exc_class.code
  630. else:
  631. return exc_class, None
  632. def _endpoint_from_view_func(view_func: t.Callable) -> str:
  633. """Internal helper that returns the default endpoint for a given
  634. function. This always is the function name.
  635. """
  636. assert view_func is not None, "expected view func if endpoint is not provided."
  637. return view_func.__name__
  638. def _matching_loader_thinks_module_is_package(loader, mod_name):
  639. """Attempt to figure out if the given name is a package or a module.
  640. :param: loader: The loader that handled the name.
  641. :param mod_name: The name of the package or module.
  642. """
  643. # Use loader.is_package if it's available.
  644. if hasattr(loader, "is_package"):
  645. return loader.is_package(mod_name)
  646. cls = type(loader)
  647. # NamespaceLoader doesn't implement is_package, but all names it
  648. # loads must be packages.
  649. if cls.__module__ == "_frozen_importlib" and cls.__name__ == "NamespaceLoader":
  650. return True
  651. # Otherwise we need to fail with an error that explains what went
  652. # wrong.
  653. raise AttributeError(
  654. f"'{cls.__name__}.is_package()' must be implemented for PEP 302"
  655. f" import hooks."
  656. )
  657. def _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool:
  658. # Path.is_relative_to doesn't exist until Python 3.9
  659. try:
  660. path.relative_to(base)
  661. return True
  662. except ValueError:
  663. return False
  664. def _find_package_path(import_name):
  665. """Find the path that contains the package or module."""
  666. root_mod_name, _, _ = import_name.partition(".")
  667. try:
  668. root_spec = importlib.util.find_spec(root_mod_name)
  669. if root_spec is None:
  670. raise ValueError("not found")
  671. # ImportError: the machinery told us it does not exist
  672. # ValueError:
  673. # - the module name was invalid
  674. # - the module name is __main__
  675. # - *we* raised `ValueError` due to `root_spec` being `None`
  676. except (ImportError, ValueError):
  677. pass # handled below
  678. else:
  679. # namespace package
  680. if root_spec.origin in {"namespace", None}:
  681. package_spec = importlib.util.find_spec(import_name)
  682. if package_spec is not None and package_spec.submodule_search_locations:
  683. # Pick the path in the namespace that contains the submodule.
  684. package_path = pathlib.Path(
  685. os.path.commonpath(package_spec.submodule_search_locations)
  686. )
  687. search_locations = (
  688. location
  689. for location in root_spec.submodule_search_locations
  690. if _path_is_relative_to(package_path, location)
  691. )
  692. else:
  693. # Pick the first path.
  694. search_locations = iter(root_spec.submodule_search_locations)
  695. return os.path.dirname(next(search_locations))
  696. # a package (with __init__.py)
  697. elif root_spec.submodule_search_locations:
  698. return os.path.dirname(os.path.dirname(root_spec.origin))
  699. # just a normal module
  700. else:
  701. return os.path.dirname(root_spec.origin)
  702. # we were unable to find the `package_path` using PEP 451 loaders
  703. loader = pkgutil.get_loader(root_mod_name)
  704. if loader is None or root_mod_name == "__main__":
  705. # import name is not found, or interactive/main module
  706. return os.getcwd()
  707. if hasattr(loader, "get_filename"):
  708. filename = loader.get_filename(root_mod_name)
  709. elif hasattr(loader, "archive"):
  710. # zipimporter's loader.archive points to the .egg or .zip file.
  711. filename = loader.archive
  712. else:
  713. # At least one loader is missing both get_filename and archive:
  714. # Google App Engine's HardenedModulesHook, use __file__.
  715. filename = importlib.import_module(root_mod_name).__file__
  716. package_path = os.path.abspath(os.path.dirname(filename))
  717. # If the imported name is a package, filename is currently pointing
  718. # to the root of the package, need to get the current directory.
  719. if _matching_loader_thinks_module_is_package(loader, root_mod_name):
  720. package_path = os.path.dirname(package_path)
  721. return package_path
  722. def find_package(import_name: str):
  723. """Find the prefix that a package is installed under, and the path
  724. that it would be imported from.
  725. The prefix is the directory containing the standard directory
  726. hierarchy (lib, bin, etc.). If the package is not installed to the
  727. system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),
  728. ``None`` is returned.
  729. The path is the entry in :attr:`sys.path` that contains the package
  730. for import. If the package is not installed, it's assumed that the
  731. package was imported from the current working directory.
  732. """
  733. package_path = _find_package_path(import_name)
  734. py_prefix = os.path.abspath(sys.prefix)
  735. # installed to the system
  736. if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):
  737. return py_prefix, package_path
  738. site_parent, site_folder = os.path.split(package_path)
  739. # installed to a virtualenv
  740. if site_folder.lower() == "site-packages":
  741. parent, folder = os.path.split(site_parent)
  742. # Windows (prefix/lib/site-packages)
  743. if folder.lower() == "lib":
  744. return parent, package_path
  745. # Unix (prefix/lib/pythonX.Y/site-packages)
  746. if os.path.basename(parent).lower() == "lib":
  747. return os.path.dirname(parent), package_path
  748. # something else (prefix/site-packages)
  749. return site_parent, package_path
  750. # not installed
  751. return None, package_path