anydi 0.50.0__py3-none-any.whl → 0.52.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,8 @@
1
- from ._container import container
2
- from ._utils import inject_urlpatterns, register_components, register_settings
3
-
4
- __all__ = [
5
- "container",
6
- "register_components",
7
- "register_settings",
8
- "inject_urlpatterns",
9
- ]
1
+ raise ImportError(
2
+ "The Django extension requires additional dependencies.\n\n"
3
+ "Install one of the following extras:\n"
4
+ " pip install 'anydi-django' # for Django\n"
5
+ " pip install 'anydi-django[ninja]' # for Django Ninja\n\n"
6
+ "Then, instead of importing from 'anydi.ext.django', import directly from:\n"
7
+ " import anydi_django\n"
8
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: anydi
3
- Version: 0.50.0
3
+ Version: 0.52.0
4
4
  Summary: Dependency Injection library
5
5
  Keywords: dependency injection,dependencies,di,async,asyncio,application
6
6
  Author: Anton Ruhlov
@@ -140,6 +140,12 @@ anydi.ext.fastapi.install(app, container)
140
140
 
141
141
  ## Django Ninja Example
142
142
 
143
+ ### Install
144
+
145
+ ```sh
146
+ pip install 'anydi-django[ninja]'
147
+ ```
148
+
143
149
  *container.py*
144
150
 
145
151
  ```python
@@ -161,7 +167,7 @@ def get_container() -> Container:
161
167
  ```python
162
168
  INSTALLED_APPS = [
163
169
  ...
164
- "anydi.ext.django",
170
+ "anydi_django",
165
171
  ]
166
172
 
167
173
  ANYDI = {
@@ -9,15 +9,7 @@ anydi/_scan.py,sha256=SoB9uugaZVqBIW2IMKQGbu9YGaWHT3BhKWrDpiQaINE,3634
9
9
  anydi/_scope.py,sha256=PFHjPb2-n0vhRo9mvD_craTFfoJBzR3y-N3_0apL5Q0,258
10
10
  anydi/_typing.py,sha256=LXOmWua-UimL9te8Ye3u3MCLiA7EzNhDuacw4kgnxP4,2877
11
11
  anydi/ext/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
- anydi/ext/django/__init__.py,sha256=QI1IABCVgSDTUoh7M9WMECKXwB3xvh04HfQ9TOWw1Mk,223
13
- anydi/ext/django/_container.py,sha256=cxVoYQG16WP0S_Yv4TnLwuaaT7NVEOhLWO-YdALJUb4,418
14
- anydi/ext/django/_settings.py,sha256=NsYbFBeslqw_tcXCn2b2gKnSp7eb64DM4dRc4tn_eiw,808
15
- anydi/ext/django/_utils.py,sha256=sYfUgBV9azddWYB4vNaZadDXcv_MiU-wSfVKV-TZDrE,2695
16
- anydi/ext/django/apps.py,sha256=vlsufhXRQbQOBWBTVOKJT3X2lCUWKWTVIKxqoZUVeps,2992
17
- anydi/ext/django/middleware.py,sha256=dL__Ff6fCK0GzIcncsVC3px8JCszSk-wSq5x2hiNM5s,881
18
- anydi/ext/django/ninja/__init__.py,sha256=4J0zoHPK9itbTVrjjvLX6Ftrsb2ND8bITqNDIJzEhks,520
19
- anydi/ext/django/ninja/_operation.py,sha256=wk5EOjLY3KVIHk9jMCGsFsja9-dQmMOpLpHXciqxQdk,2680
20
- anydi/ext/django/ninja/_signature.py,sha256=p7JtyMdFhX4fWQOvAhvZNss6iURNERcdsTsQADTHkMY,2358
12
+ anydi/ext/django/__init__.py,sha256=Ve8lncLU9dPY_Vjt4zihPgsSxwAtFHACn0XvBM5JG8k,367
21
13
  anydi/ext/fastapi.py,sha256=L9VGPHGy23se1sflmJqTE7LNfQuElVdYEogoT1f5-4A,2324
22
14
  anydi/ext/faststream.py,sha256=Dy81Vf34CP6pEIbZ-41vh_-Dn6Qc-rcf14U5poebjxI,1905
23
15
  anydi/ext/pydantic_settings.py,sha256=0GQjw7QpQlT5p6GxFClXYdtc6J42PClmAnRWPEzMjvY,1488
@@ -26,7 +18,7 @@ anydi/ext/starlette/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSu
26
18
  anydi/ext/starlette/middleware.py,sha256=MxnzshAs-CMvjJp0r457k52MzBL8O4KAuClnF6exBdU,803
27
19
  anydi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
28
20
  anydi/testing.py,sha256=gbQnJ6qFaQ5qbUwFWfSJ67SKhxLuPzwLGidistsmHk8,5519
29
- anydi-0.50.0.dist-info/WHEEL,sha256=eh7sammvW2TypMMMGKgsM83HyA_3qQ5Lgg3ynoecH3M,79
30
- anydi-0.50.0.dist-info/entry_points.txt,sha256=AgOcQYM5KyS4D37QcYb00tiid0QA-pD1VrjHHq4QAps,44
31
- anydi-0.50.0.dist-info/METADATA,sha256=sYMf1a1xJfwEzJjGYDrVFT0sVEi_80XVRtb_JwrQF0Y,4968
32
- anydi-0.50.0.dist-info/RECORD,,
21
+ anydi-0.52.0.dist-info/WHEEL,sha256=eh7sammvW2TypMMMGKgsM83HyA_3qQ5Lgg3ynoecH3M,79
22
+ anydi-0.52.0.dist-info/entry_points.txt,sha256=AgOcQYM5KyS4D37QcYb00tiid0QA-pD1VrjHHq4QAps,44
23
+ anydi-0.52.0.dist-info/METADATA,sha256=GvHhlEF-L72OAvA-6fuFzjUnvOlvM16T8MpZXT1vSbA,5022
24
+ anydi-0.52.0.dist-info/RECORD,,
@@ -1,18 +0,0 @@
1
- from typing import cast
2
-
3
- from django.apps.registry import apps
4
- from django.utils.functional import SimpleLazyObject
5
-
6
- import anydi
7
-
8
- from .apps import ContainerConfig
9
-
10
- __all__ = ["container"]
11
-
12
-
13
- def _get_container() -> anydi.Container:
14
- app_config = cast(ContainerConfig, apps.get_app_config(ContainerConfig.label))
15
- return app_config.container
16
-
17
-
18
- container = cast(anydi.Container, SimpleLazyObject(_get_container))
@@ -1,37 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from collections.abc import Sequence
4
-
5
- from django.conf import settings
6
- from typing_extensions import TypedDict
7
-
8
-
9
- class Settings(TypedDict):
10
- CONTAINER_FACTORY: str | None
11
- REGISTER_SETTINGS: bool
12
- REGISTER_COMPONENTS: bool
13
- INJECT_URLCONF: str | Sequence[str] | None
14
- MODULES: Sequence[str]
15
- SCAN_PACKAGES: Sequence[str]
16
- PATCH_NINJA: bool
17
-
18
-
19
- DEFAULTS = Settings(
20
- CONTAINER_FACTORY=None,
21
- REGISTER_SETTINGS=False,
22
- REGISTER_COMPONENTS=False,
23
- MODULES=[],
24
- PATCH_NINJA=False,
25
- INJECT_URLCONF=None,
26
- SCAN_PACKAGES=[],
27
- )
28
-
29
-
30
- def get_settings() -> Settings:
31
- """Get the AnyDI settings from the Django settings."""
32
- return Settings(
33
- **{
34
- **DEFAULTS,
35
- **getattr(settings, "ANYDI", {}),
36
- }
37
- )
@@ -1,89 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from collections.abc import Iterator
4
- from typing import Annotated, Any
5
-
6
- from django.conf import settings
7
- from django.core.cache import BaseCache, caches
8
- from django.db import connections
9
- from django.db.backends.base.base import BaseDatabaseWrapper
10
- from django.urls import URLPattern, URLResolver, get_resolver
11
-
12
- from anydi import Container
13
-
14
-
15
- def register_settings(
16
- container: Container, prefix: str = "django.conf.settings."
17
- ) -> None:
18
- """Register Django settings into the container."""
19
-
20
- # Ensure prefix ends with a dot
21
- if prefix[-1] != ".":
22
- prefix += "."
23
-
24
- for setting_name in dir(settings):
25
- setting_value = getattr(settings, setting_name)
26
- if not setting_name.isupper():
27
- continue
28
-
29
- container.register(
30
- Annotated[type(setting_value), f"{prefix}{setting_name}"],
31
- _get_setting_value(setting_value),
32
- scope="singleton",
33
- )
34
-
35
-
36
- def register_components(container: Container) -> None:
37
- """Register Django components into the container."""
38
-
39
- # Register caches
40
- def _get_cache(cache_name: str) -> Any:
41
- return lambda: caches[cache_name]
42
-
43
- for cache_name in caches:
44
- container.register(
45
- Annotated[BaseCache, cache_name],
46
- _get_cache(cache_name),
47
- scope="singleton",
48
- )
49
-
50
- # Register database connections
51
- def _get_connection(alias: str) -> Any:
52
- return lambda: connections[alias]
53
-
54
- for alias in connections:
55
- container.register(
56
- Annotated[BaseDatabaseWrapper, alias],
57
- _get_connection(alias),
58
- scope="singleton",
59
- )
60
-
61
-
62
- def inject_urlpatterns(container: Container, *, urlconf: str) -> None:
63
- """Auto-inject the container into views."""
64
- resolver = get_resolver(urlconf)
65
- injected_urlpatterns = []
66
- for pattern in iter_urlpatterns(resolver.url_patterns):
67
- # Skip already injected views
68
- if pattern.lookup_str in injected_urlpatterns:
69
- continue
70
- # Skip django-ninja views
71
- if pattern.lookup_str.startswith("ninja."):
72
- continue # pragma: no cover
73
- pattern.callback = container.inject(pattern.callback)
74
- injected_urlpatterns.append(pattern.lookup_str)
75
-
76
-
77
- def iter_urlpatterns(
78
- urlpatterns: list[URLPattern | URLResolver],
79
- ) -> Iterator[URLPattern]:
80
- """Iterate over all views in urlpatterns."""
81
- for url_pattern in urlpatterns:
82
- if isinstance(url_pattern, URLResolver):
83
- yield from iter_urlpatterns(url_pattern.url_patterns)
84
- else:
85
- yield url_pattern
86
-
87
-
88
- def _get_setting_value(value: Any) -> Any:
89
- return lambda: value
anydi/ext/django/apps.py DELETED
@@ -1,89 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import types
4
- from collections.abc import Callable
5
- from typing import cast
6
-
7
- from django.apps import AppConfig
8
- from django.conf import settings
9
- from django.core.exceptions import ImproperlyConfigured
10
- from django.utils.module_loading import import_string
11
-
12
- import anydi
13
- from anydi.testing import TestContainer
14
-
15
- from ._settings import get_settings
16
- from ._utils import inject_urlpatterns, register_components, register_settings
17
-
18
-
19
- class ContainerConfig(AppConfig):
20
- name = "anydi.ext.django"
21
- label = "anydi_django"
22
-
23
- def __init__(self, app_name: str, app_module: types.ModuleType | None) -> None:
24
- super().__init__(app_name, app_module)
25
- self.settings = get_settings()
26
- # Create a container
27
- container_factory_path = self.settings["CONTAINER_FACTORY"]
28
- if container_factory_path:
29
- try:
30
- container_factory = cast(
31
- Callable[[], anydi.Container], import_string(container_factory_path)
32
- )
33
- except ImportError as exc:
34
- raise ImproperlyConfigured(
35
- f"Cannot import container factory '{container_factory_path}'."
36
- ) from exc
37
- container = container_factory()
38
- else:
39
- container = anydi.Container()
40
-
41
- # Use test container
42
- testing = getattr(settings, "ANYDI_TESTING", False)
43
- if testing:
44
- container = TestContainer.from_container(container)
45
-
46
- self.container = container
47
-
48
- def ready(self) -> None: # noqa: C901
49
- # Register Django settings
50
- if self.settings["REGISTER_SETTINGS"]:
51
- register_settings(
52
- self.container,
53
- prefix=getattr(
54
- settings,
55
- "ANYDI_SETTINGS_PREFIX",
56
- "django.conf.settings.",
57
- ),
58
- )
59
-
60
- # Register Django components
61
- if self.settings["REGISTER_COMPONENTS"]:
62
- register_components(self.container)
63
-
64
- # Register modules
65
- for module_path in self.settings["MODULES"]:
66
- try:
67
- module_cls = import_string(module_path)
68
- except ImportError as exc:
69
- raise ImproperlyConfigured(
70
- f"Cannot import module '{module_path}'."
71
- ) from exc
72
- self.container.register_module(module_cls)
73
-
74
- # Patching the django-ninja framework if it installed
75
- if self.settings["PATCH_NINJA"]:
76
- from .ninja import patch_ninja
77
-
78
- patch_ninja()
79
-
80
- # Auto-injecting the container into views
81
- if urlconf := self.settings["INJECT_URLCONF"]:
82
- if isinstance(urlconf, str):
83
- urlconf = [urlconf]
84
- for u in urlconf:
85
- inject_urlpatterns(self.container, urlconf=u)
86
-
87
- # Scan packages
88
- for scan_package in self.settings["SCAN_PACKAGES"]:
89
- self.container.scan(scan_package)
@@ -1,29 +0,0 @@
1
- from collections.abc import Callable
2
- from typing import Any
3
-
4
- from asgiref.sync import iscoroutinefunction
5
- from django.http import HttpRequest
6
- from django.utils.decorators import sync_and_async_middleware
7
-
8
- from ._container import container
9
-
10
-
11
- @sync_and_async_middleware
12
- def request_scoped_middleware(
13
- get_response: Callable[..., Any],
14
- ) -> Callable[..., Any]:
15
- if iscoroutinefunction(get_response):
16
-
17
- async def async_middleware(request: HttpRequest) -> Any:
18
- async with container.arequest_context() as context:
19
- context.set(HttpRequest, request)
20
- return await get_response(request)
21
-
22
- return async_middleware
23
-
24
- def middleware(request: HttpRequest) -> Any:
25
- with container.request_context() as context:
26
- context.set(HttpRequest, request)
27
- return get_response(request)
28
-
29
- return middleware
@@ -1,16 +0,0 @@
1
- try:
2
- from ninja import operation
3
- except ImportError as exc: # pragma: no cover
4
- raise ImportError(
5
- "'django-ninja' is not installed. "
6
- "Please install it using 'pip install django-ninja'."
7
- ) from exc
8
-
9
- from ._operation import AsyncOperation, Operation
10
- from ._signature import ViewSignature
11
-
12
-
13
- def patch_ninja() -> None:
14
- operation.ViewSignature = ViewSignature # type: ignore
15
- operation.Operation = Operation # type: ignore
16
- operation.AsyncOperation = AsyncOperation # type: ignore
@@ -1,75 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import Any
4
-
5
- from django.http import HttpRequest, HttpResponseBase
6
- from ninja.operation import (
7
- AsyncOperation as BaseAsyncOperation, # noqa
8
- Operation as BaseOperation,
9
- )
10
-
11
- from anydi.ext.django import container
12
-
13
- from ._signature import ViewSignature
14
-
15
-
16
- def _update_exc_args(exc: Exception) -> None:
17
- if isinstance(exc, TypeError) and "required positional argument" in str(exc):
18
- msg = "Did you fail to use functools.wraps() in a decorator?"
19
- msg = f"{exc.args[0]}: {msg}" if exc.args else msg
20
- exc.args = (msg,) + exc.args[1:]
21
-
22
-
23
- class Operation(BaseOperation):
24
- signature: ViewSignature
25
-
26
- def __init__(self, *args: Any, **kwargs: Any) -> None:
27
- super().__init__(*args, **kwargs)
28
- self.dependencies = self.signature.dependencies
29
-
30
- def run(self, request: HttpRequest, **kw: Any) -> HttpResponseBase:
31
- error = self._run_checks(request)
32
- if error:
33
- return error
34
- try:
35
- temporal_response = self.api.create_temporal_response(request)
36
- values = self._get_values(request, kw, temporal_response)
37
- values.update(self._get_dependencies())
38
- result = self.view_func(request, **values)
39
- return self._result_to_response(request, result, temporal_response)
40
- except Exception as e:
41
- _update_exc_args(e)
42
- return self.api.on_exception(request, e)
43
-
44
- def _get_dependencies(self) -> dict[str, Any]:
45
- return {
46
- name: container.resolve(interface) for name, interface in self.dependencies
47
- }
48
-
49
-
50
- class AsyncOperation(BaseAsyncOperation):
51
- signature: ViewSignature
52
-
53
- def __init__(self, *args: Any, **kwargs: Any) -> None:
54
- super().__init__(*args, **kwargs)
55
- self.dependencies = self.signature.dependencies
56
-
57
- async def run(self, request: HttpRequest, **kw: Any) -> HttpResponseBase:
58
- error = await self._run_checks(request)
59
- if error:
60
- return error
61
- try:
62
- temporal_response = self.api.create_temporal_response(request)
63
- values = self._get_values(request, kw, temporal_response)
64
- values.update(await self._get_dependencies())
65
- result = await self.view_func(request, **values)
66
- return self._result_to_response(request, result, temporal_response)
67
- except Exception as e:
68
- _update_exc_args(e)
69
- return self.api.on_exception(request, e)
70
-
71
- async def _get_dependencies(self) -> dict[str, Any]:
72
- return {
73
- name: await container.aresolve(interface)
74
- for name, interface in self.dependencies
75
- }
@@ -1,68 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import inspect
4
- from collections.abc import Callable
5
- from typing import Any
6
-
7
- from django.http import HttpResponse
8
- from ninja.signature.details import (
9
- FuncParam, # noqa
10
- ViewSignature as BaseViewSignature,
11
- )
12
- from ninja.signature.utils import get_path_param_names, get_typed_signature
13
-
14
- from anydi._typing import is_inject_marker # noqa
15
- from anydi.ext.django import container
16
-
17
-
18
- class ViewSignature(BaseViewSignature):
19
- def __init__(self, path: str, view_func: Callable[..., Any]) -> None:
20
- self.view_func = view_func
21
- self.signature = get_typed_signature(self.view_func)
22
- self.path = path
23
- self.path_params_names = get_path_param_names(path)
24
- self.docstring = inspect.cleandoc(view_func.__doc__ or "")
25
- self.has_kwargs = False
26
- self.dependencies = []
27
-
28
- self.params = []
29
- for name, arg in self.signature.parameters.items():
30
- if name == "request":
31
- # TODO: maybe better assert that 1st param is request or check by type?
32
- # maybe even have attribute like `has_request`
33
- # so that users can ignore passing request if not needed
34
- continue
35
-
36
- if arg.kind == arg.VAR_KEYWORD:
37
- # Skipping **kwargs
38
- self.has_kwargs = True
39
- continue
40
-
41
- if arg.kind == arg.VAR_POSITIONAL:
42
- # Skipping *args
43
- continue
44
-
45
- if arg.annotation is HttpResponse:
46
- self.response_arg = name
47
- continue
48
-
49
- interface, should_inject = container.validate_injected_parameter(
50
- arg, call=self.view_func
51
- )
52
- if should_inject:
53
- self.dependencies.append((name, interface))
54
- continue
55
-
56
- func_param = self._get_param_type(name, arg)
57
- self.params.append(func_param)
58
-
59
- ninja_contribute_args = getattr(view_func, "_ninja_contribute_args", None)
60
- if ninja_contribute_args is not None:
61
- for p_name, p_type, p_source in ninja_contribute_args:
62
- self.params.append(
63
- FuncParam(p_name, p_source.alias or p_name, p_source, p_type, False)
64
- )
65
-
66
- self.models = self._create_models()
67
-
68
- self._validate_view_path_params()
File without changes