scaffold.py 33 KB

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