scaffold.py 33 KB

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