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