You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

865 lines
32KB

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