scaffold.py 32 KB

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