scaffold.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. import importlib.util
  2. import os
  3. import pkgutil
  4. import sys
  5. import typing as t
  6. from collections import defaultdict
  7. from functools import update_wrapper
  8. from json import JSONDecoder
  9. from json import JSONEncoder
  10. from jinja2 import FileSystemLoader
  11. from werkzeug.exceptions import default_exceptions
  12. from werkzeug.exceptions import HTTPException
  13. from .cli import AppGroup
  14. from .globals import current_app
  15. from .helpers import get_root_path
  16. from .helpers import locked_cached_property
  17. from .helpers import send_from_directory
  18. from .templating import _default_template_ctx_processor
  19. from .typing import AfterRequestCallable
  20. from .typing import AppOrBlueprintKey
  21. from .typing import BeforeRequestCallable
  22. from .typing import TeardownCallable
  23. from .typing import TemplateContextProcessorCallable
  24. from .typing import URLDefaultCallable
  25. from .typing import URLValuePreprocessorCallable
  26. if t.TYPE_CHECKING:
  27. from .wrappers import Response
  28. from .typing import ErrorHandlerCallable
  29. # a singleton sentinel value for parameter defaults
  30. _sentinel = object()
  31. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  32. def setupmethod(f: F) -> F:
  33. """Wraps a method so that it performs a check in debug mode if the
  34. first request was already handled.
  35. """
  36. def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
  37. if self._is_setup_finished():
  38. raise AssertionError(
  39. "A setup function was called after the first request "
  40. "was handled. This usually indicates a bug in the"
  41. " application where a module was not imported and"
  42. " decorators or other functionality was called too"
  43. " late.\nTo fix this make sure to import all your view"
  44. " modules, database models, and everything related at a"
  45. " central place before the application starts serving"
  46. " requests."
  47. )
  48. return f(self, *args, **kwargs)
  49. return t.cast(F, update_wrapper(wrapper_func, f))
  50. class Scaffold:
  51. """Common behavior shared between :class:`~flask.Flask` and
  52. :class:`~flask.blueprints.Blueprint`.
  53. :param import_name: The import name of the module where this object
  54. is defined. Usually :attr:`__name__` should be used.
  55. :param static_folder: Path to a folder of static files to serve.
  56. If this is set, a static route will be added.
  57. :param static_url_path: URL prefix for the static route.
  58. :param template_folder: Path to a folder containing template files.
  59. for rendering. If this is set, a Jinja loader will be added.
  60. :param root_path: The path that static, template, and resource files
  61. are relative to. Typically not set, it is discovered based on
  62. the ``import_name``.
  63. .. versionadded:: 2.0
  64. """
  65. name: str
  66. _static_folder: t.Optional[str] = None
  67. _static_url_path: t.Optional[str] = None
  68. #: JSON encoder class used by :func:`flask.json.dumps`. If a
  69. #: blueprint sets this, it will be used instead of the app's value.
  70. json_encoder: t.Optional[t.Type[JSONEncoder]] = None
  71. #: JSON decoder class used by :func:`flask.json.loads`. If a
  72. #: blueprint sets this, it will be used instead of the app's value.
  73. json_decoder: t.Optional[t.Type[JSONDecoder]] = 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. AppOrBlueprintKey,
  123. t.Dict[t.Optional[int], t.Dict[t.Type[Exception], "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. AppOrBlueprintKey, t.List[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. AppOrBlueprintKey, t.List[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. AppOrBlueprintKey, t.List[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. AppOrBlueprintKey, t.List[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. AppOrBlueprintKey,
  192. t.List[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. AppOrBlueprintKey, t.List[URLDefaultCallable]
  207. ] = defaultdict(list)
  208. def __repr__(self) -> str:
  209. return f"<{type(self).__name__} {self.name!r}>"
  210. def _is_setup_finished(self) -> bool:
  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.send_file_max_age_default
  261. if value is None:
  262. return None
  263. return int(value.total_seconds())
  264. def send_static_file(self, filename: str) -> "Response":
  265. """The view function used to serve files from
  266. :attr:`static_folder`. A route is automatically registered for
  267. this view at :attr:`static_url_path` if :attr:`static_folder` is
  268. set.
  269. .. versionadded:: 0.5
  270. """
  271. if not self.has_static_folder:
  272. raise RuntimeError("'static_folder' must be set to serve static_files.")
  273. # send_file only knows to call get_send_file_max_age on the app,
  274. # call it here so it works for blueprints too.
  275. max_age = self.get_send_file_max_age(filename)
  276. return send_from_directory(
  277. t.cast(str, self.static_folder), filename, max_age=max_age
  278. )
  279. @locked_cached_property
  280. def jinja_loader(self) -> t.Optional[FileSystemLoader]:
  281. """The Jinja loader for this object's templates. By default this
  282. is a class :class:`jinja2.loaders.FileSystemLoader` to
  283. :attr:`template_folder` if it is set.
  284. .. versionadded:: 0.5
  285. """
  286. if self.template_folder is not None:
  287. return FileSystemLoader(os.path.join(self.root_path, self.template_folder))
  288. else:
  289. return None
  290. def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
  291. """Open a resource file relative to :attr:`root_path` for
  292. reading.
  293. For example, if the file ``schema.sql`` is next to the file
  294. ``app.py`` where the ``Flask`` app is defined, it can be opened
  295. with:
  296. .. code-block:: python
  297. with app.open_resource("schema.sql") as f:
  298. conn.executescript(f.read())
  299. :param resource: Path to the resource relative to
  300. :attr:`root_path`.
  301. :param mode: Open the file in this mode. Only reading is
  302. supported, valid values are "r" (or "rt") and "rb".
  303. """
  304. if mode not in {"r", "rt", "rb"}:
  305. raise ValueError("Resources can only be opened for reading.")
  306. return open(os.path.join(self.root_path, resource), mode)
  307. def _method_route(
  308. self,
  309. method: str,
  310. rule: str,
  311. options: dict,
  312. ) -> t.Callable[[F], F]:
  313. if "methods" in options:
  314. raise TypeError("Use the 'route' decorator to use the 'methods' argument.")
  315. return self.route(rule, methods=[method], **options)
  316. def get(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
  317. """Shortcut for :meth:`route` with ``methods=["GET"]``.
  318. .. versionadded:: 2.0
  319. """
  320. return self._method_route("GET", rule, options)
  321. def post(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
  322. """Shortcut for :meth:`route` with ``methods=["POST"]``.
  323. .. versionadded:: 2.0
  324. """
  325. return self._method_route("POST", rule, options)
  326. def put(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
  327. """Shortcut for :meth:`route` with ``methods=["PUT"]``.
  328. .. versionadded:: 2.0
  329. """
  330. return self._method_route("PUT", rule, options)
  331. def delete(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
  332. """Shortcut for :meth:`route` with ``methods=["DELETE"]``.
  333. .. versionadded:: 2.0
  334. """
  335. return self._method_route("DELETE", rule, options)
  336. def patch(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
  337. """Shortcut for :meth:`route` with ``methods=["PATCH"]``.
  338. .. versionadded:: 2.0
  339. """
  340. return self._method_route("PATCH", rule, options)
  341. def route(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:
  342. """Decorate a view function to register it with the given URL
  343. rule and options. Calls :meth:`add_url_rule`, which has more
  344. details about the implementation.
  345. .. code-block:: python
  346. @app.route("/")
  347. def index():
  348. return "Hello, World!"
  349. See :ref:`url-route-registrations`.
  350. The endpoint name for the route defaults to the name of the view
  351. function if the ``endpoint`` parameter isn't passed.
  352. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
  353. ``OPTIONS`` are added automatically.
  354. :param rule: The URL rule string.
  355. :param options: Extra options passed to the
  356. :class:`~werkzeug.routing.Rule` object.
  357. """
  358. def decorator(f: F) -> F:
  359. endpoint = options.pop("endpoint", None)
  360. self.add_url_rule(rule, endpoint, f, **options)
  361. return f
  362. return decorator
  363. @setupmethod
  364. def add_url_rule(
  365. self,
  366. rule: str,
  367. endpoint: t.Optional[str] = None,
  368. view_func: t.Optional[t.Callable] = None,
  369. provide_automatic_options: t.Optional[bool] = None,
  370. **options: t.Any,
  371. ) -> None:
  372. """Register a rule for routing incoming requests and building
  373. URLs. The :meth:`route` decorator is a shortcut to call this
  374. with the ``view_func`` argument. These are equivalent:
  375. .. code-block:: python
  376. @app.route("/")
  377. def index():
  378. ...
  379. .. code-block:: python
  380. def index():
  381. ...
  382. app.add_url_rule("/", view_func=index)
  383. See :ref:`url-route-registrations`.
  384. The endpoint name for the route defaults to the name of the view
  385. function if the ``endpoint`` parameter isn't passed. An error
  386. will be raised if a function has already been registered for the
  387. endpoint.
  388. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is
  389. always added automatically, and ``OPTIONS`` is added
  390. automatically by default.
  391. ``view_func`` does not necessarily need to be passed, but if the
  392. rule should participate in routing an endpoint name must be
  393. associated with a view function at some point with the
  394. :meth:`endpoint` decorator.
  395. .. code-block:: python
  396. app.add_url_rule("/", endpoint="index")
  397. @app.endpoint("index")
  398. def index():
  399. ...
  400. If ``view_func`` has a ``required_methods`` attribute, those
  401. methods are added to the passed and automatic methods. If it
  402. has a ``provide_automatic_methods`` attribute, it is used as the
  403. default if the parameter is not passed.
  404. :param rule: The URL rule string.
  405. :param endpoint: The endpoint name to associate with the rule
  406. and view function. Used when routing and building URLs.
  407. Defaults to ``view_func.__name__``.
  408. :param view_func: The view function to associate with the
  409. endpoint name.
  410. :param provide_automatic_options: Add the ``OPTIONS`` method and
  411. respond to ``OPTIONS`` requests automatically.
  412. :param options: Extra options passed to the
  413. :class:`~werkzeug.routing.Rule` object.
  414. """
  415. raise NotImplementedError
  416. def endpoint(self, endpoint: str) -> t.Callable:
  417. """Decorate a view function to register it for the given
  418. endpoint. Used if a rule is added without a ``view_func`` with
  419. :meth:`add_url_rule`.
  420. .. code-block:: python
  421. app.add_url_rule("/ex", endpoint="example")
  422. @app.endpoint("example")
  423. def example():
  424. ...
  425. :param endpoint: The endpoint name to associate with the view
  426. function.
  427. """
  428. def decorator(f):
  429. self.view_functions[endpoint] = f
  430. return f
  431. return decorator
  432. @setupmethod
  433. def before_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:
  434. """Register a function to run before each request.
  435. For example, this can be used to open a database connection, or
  436. to load the logged in user from the session.
  437. .. code-block:: python
  438. @app.before_request
  439. def load_user():
  440. if "user_id" in session:
  441. g.user = db.session.get(session["user_id"])
  442. The function will be called without any arguments. If it returns
  443. a non-``None`` value, the value is handled as if it was the
  444. return value from the view, and further request handling is
  445. stopped.
  446. """
  447. self.before_request_funcs.setdefault(None, []).append(f)
  448. return f
  449. @setupmethod
  450. def after_request(self, f: AfterRequestCallable) -> AfterRequestCallable:
  451. """Register a function to run after each request to this object.
  452. The function is called with the response object, and must return
  453. a response object. This allows the functions to modify or
  454. replace the response before it is sent.
  455. If a function raises an exception, any remaining
  456. ``after_request`` functions will not be called. Therefore, this
  457. should not be used for actions that must execute, such as to
  458. close resources. Use :meth:`teardown_request` for that.
  459. """
  460. self.after_request_funcs.setdefault(None, []).append(f)
  461. return f
  462. @setupmethod
  463. def teardown_request(self, f: TeardownCallable) -> TeardownCallable:
  464. """Register a function to be run at the end of each request,
  465. regardless of whether there was an exception or not. These functions
  466. are executed when the request context is popped, even if not an
  467. actual request was performed.
  468. Example::
  469. ctx = app.test_request_context()
  470. ctx.push()
  471. ...
  472. ctx.pop()
  473. When ``ctx.pop()`` is executed in the above example, the teardown
  474. functions are called just before the request context moves from the
  475. stack of active contexts. This becomes relevant if you are using
  476. such constructs in tests.
  477. Teardown functions must avoid raising exceptions. If
  478. they execute code that might fail they
  479. will have to surround the execution of that code with try/except
  480. statements and log any errors.
  481. When a teardown function was called because of an exception it will
  482. be passed an error object.
  483. The return values of teardown functions are ignored.
  484. .. admonition:: Debug Note
  485. In debug mode Flask will not tear down a request on an exception
  486. immediately. Instead it will keep it alive so that the interactive
  487. debugger can still access it. This behavior can be controlled
  488. by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
  489. """
  490. self.teardown_request_funcs.setdefault(None, []).append(f)
  491. return f
  492. @setupmethod
  493. def context_processor(
  494. self, f: TemplateContextProcessorCallable
  495. ) -> TemplateContextProcessorCallable:
  496. """Registers a template context processor function."""
  497. self.template_context_processors[None].append(f)
  498. return f
  499. @setupmethod
  500. def url_value_preprocessor(
  501. self, f: URLValuePreprocessorCallable
  502. ) -> URLValuePreprocessorCallable:
  503. """Register a URL value preprocessor function for all view
  504. functions in the application. These functions will be called before the
  505. :meth:`before_request` functions.
  506. The function can modify the values captured from the matched url before
  507. they are passed to the view. For example, this can be used to pop a
  508. common language code value and place it in ``g`` rather than pass it to
  509. every view.
  510. The function is passed the endpoint name and values dict. The return
  511. value is ignored.
  512. """
  513. self.url_value_preprocessors[None].append(f)
  514. return f
  515. @setupmethod
  516. def url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:
  517. """Callback function for URL defaults for all view functions of the
  518. application. It's called with the endpoint and values and should
  519. update the values passed in place.
  520. """
  521. self.url_default_functions[None].append(f)
  522. return f
  523. @setupmethod
  524. def errorhandler(
  525. self, code_or_exception: t.Union[t.Type[Exception], int]
  526. ) -> t.Callable[["ErrorHandlerCallable"], "ErrorHandlerCallable"]:
  527. """Register a function to handle errors by code or exception class.
  528. A decorator that is used to register a function given an
  529. error code. Example::
  530. @app.errorhandler(404)
  531. def page_not_found(error):
  532. return 'This page does not exist', 404
  533. You can also register handlers for arbitrary exceptions::
  534. @app.errorhandler(DatabaseError)
  535. def special_exception_handler(error):
  536. return 'Database connection failed', 500
  537. .. versionadded:: 0.7
  538. Use :meth:`register_error_handler` instead of modifying
  539. :attr:`error_handler_spec` directly, for application wide error
  540. handlers.
  541. .. versionadded:: 0.7
  542. One can now additionally also register custom exception types
  543. that do not necessarily have to be a subclass of the
  544. :class:`~werkzeug.exceptions.HTTPException` class.
  545. :param code_or_exception: the code as integer for the handler, or
  546. an arbitrary exception
  547. """
  548. def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":
  549. self.register_error_handler(code_or_exception, f)
  550. return f
  551. return decorator
  552. @setupmethod
  553. def register_error_handler(
  554. self,
  555. code_or_exception: t.Union[t.Type[Exception], int],
  556. f: "ErrorHandlerCallable",
  557. ) -> None:
  558. """Alternative error attach function to the :meth:`errorhandler`
  559. decorator that is more straightforward to use for non decorator
  560. usage.
  561. .. versionadded:: 0.7
  562. """
  563. if isinstance(code_or_exception, HTTPException): # old broken behavior
  564. raise ValueError(
  565. "Tried to register a handler for an exception instance"
  566. f" {code_or_exception!r}. Handlers can only be"
  567. " registered for exception classes or HTTP error codes."
  568. )
  569. try:
  570. exc_class, code = self._get_exc_class_and_code(code_or_exception)
  571. except KeyError:
  572. raise KeyError(
  573. f"'{code_or_exception}' is not a recognized HTTP error"
  574. " code. Use a subclass of HTTPException with that code"
  575. " instead."
  576. ) from None
  577. self.error_handler_spec[None][code][exc_class] = f
  578. @staticmethod
  579. def _get_exc_class_and_code(
  580. exc_class_or_code: t.Union[t.Type[Exception], int]
  581. ) -> t.Tuple[t.Type[Exception], t.Optional[int]]:
  582. """Get the exception class being handled. For HTTP status codes
  583. or ``HTTPException`` subclasses, return both the exception and
  584. status code.
  585. :param exc_class_or_code: Any exception class, or an HTTP status
  586. code as an integer.
  587. """
  588. exc_class: t.Type[Exception]
  589. if isinstance(exc_class_or_code, int):
  590. exc_class = default_exceptions[exc_class_or_code]
  591. else:
  592. exc_class = exc_class_or_code
  593. assert issubclass(
  594. exc_class, Exception
  595. ), "Custom exceptions must be subclasses of Exception."
  596. if issubclass(exc_class, HTTPException):
  597. return exc_class, exc_class.code
  598. else:
  599. return exc_class, None
  600. def _endpoint_from_view_func(view_func: t.Callable) -> str:
  601. """Internal helper that returns the default endpoint for a given
  602. function. This always is the function name.
  603. """
  604. assert view_func is not None, "expected view func if endpoint is not provided."
  605. return view_func.__name__
  606. def _matching_loader_thinks_module_is_package(loader, mod_name):
  607. """Attempt to figure out if the given name is a package or a module.
  608. :param: loader: The loader that handled the name.
  609. :param mod_name: The name of the package or module.
  610. """
  611. # Use loader.is_package if it's available.
  612. if hasattr(loader, "is_package"):
  613. return loader.is_package(mod_name)
  614. cls = type(loader)
  615. # NamespaceLoader doesn't implement is_package, but all names it
  616. # loads must be packages.
  617. if cls.__module__ == "_frozen_importlib" and cls.__name__ == "NamespaceLoader":
  618. return True
  619. # Otherwise we need to fail with an error that explains what went
  620. # wrong.
  621. raise AttributeError(
  622. f"'{cls.__name__}.is_package()' must be implemented for PEP 302"
  623. f" import hooks."
  624. )
  625. def _find_package_path(root_mod_name):
  626. """Find the path that contains the package or module."""
  627. try:
  628. spec = importlib.util.find_spec(root_mod_name)
  629. if spec is None:
  630. raise ValueError("not found")
  631. # ImportError: the machinery told us it does not exist
  632. # ValueError:
  633. # - the module name was invalid
  634. # - the module name is __main__
  635. # - *we* raised `ValueError` due to `spec` being `None`
  636. except (ImportError, ValueError):
  637. pass # handled below
  638. else:
  639. # namespace package
  640. if spec.origin in {"namespace", None}:
  641. return os.path.dirname(next(iter(spec.submodule_search_locations)))
  642. # a package (with __init__.py)
  643. elif spec.submodule_search_locations:
  644. return os.path.dirname(os.path.dirname(spec.origin))
  645. # just a normal module
  646. else:
  647. return os.path.dirname(spec.origin)
  648. # we were unable to find the `package_path` using PEP 451 loaders
  649. loader = pkgutil.get_loader(root_mod_name)
  650. if loader is None or root_mod_name == "__main__":
  651. # import name is not found, or interactive/main module
  652. return os.getcwd()
  653. if hasattr(loader, "get_filename"):
  654. filename = loader.get_filename(root_mod_name)
  655. elif hasattr(loader, "archive"):
  656. # zipimporter's loader.archive points to the .egg or .zip file.
  657. filename = loader.archive
  658. else:
  659. # At least one loader is missing both get_filename and archive:
  660. # Google App Engine's HardenedModulesHook, use __file__.
  661. filename = importlib.import_module(root_mod_name).__file__
  662. package_path = os.path.abspath(os.path.dirname(filename))
  663. # If the imported name is a package, filename is currently pointing
  664. # to the root of the package, need to get the current directory.
  665. if _matching_loader_thinks_module_is_package(loader, root_mod_name):
  666. package_path = os.path.dirname(package_path)
  667. return package_path
  668. def find_package(import_name: str):
  669. """Find the prefix that a package is installed under, and the path
  670. that it would be imported from.
  671. The prefix is the directory containing the standard directory
  672. hierarchy (lib, bin, etc.). If the package is not installed to the
  673. system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),
  674. ``None`` is returned.
  675. The path is the entry in :attr:`sys.path` that contains the package
  676. for import. If the package is not installed, it's assumed that the
  677. package was imported from the current working directory.
  678. """
  679. root_mod_name, _, _ = import_name.partition(".")
  680. package_path = _find_package_path(root_mod_name)
  681. py_prefix = os.path.abspath(sys.prefix)
  682. # installed to the system
  683. if package_path.startswith(py_prefix):
  684. return py_prefix, package_path
  685. site_parent, site_folder = os.path.split(package_path)
  686. # installed to a virtualenv
  687. if site_folder.lower() == "site-packages":
  688. parent, folder = os.path.split(site_parent)
  689. # Windows (prefix/lib/site-packages)
  690. if folder.lower() == "lib":
  691. return parent, package_path
  692. # Unix (prefix/lib/pythonX.Y/site-packages)
  693. if os.path.basename(parent).lower() == "lib":
  694. return os.path.dirname(parent), package_path
  695. # something else (prefix/site-packages)
  696. return site_parent, package_path
  697. # not installed
  698. return None, package_path