django-dishka 0.1.0__tar.gz

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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-dishka
3
+ Version: 0.1.0
4
+ Summary: Dishka dependency injection integration for Django, Django REST Framework, Django Ninja, and Django Modern Rest.
5
+ Keywords: django,dishka,dependency injection,di,ioc,django-rest-framework,drf,django-ninja,django-modern-rest,dmr,async
6
+ Author: Sergei Aleshin
7
+ Author-email: Sergei Aleshin <formats_trinket7c@icloud.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: Django
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Typing :: Typed
20
+ Requires-Dist: dishka>=1.10.1
21
+ Requires-Dist: django>=5
22
+ Requires-Python: >=3.12
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Django integration for Dishka
26
+
27
+ [![CI](https://github.com/s-aleshin/django-dishka/actions/workflows/ci.yml/badge.svg?event=push)](https://github.com/s-aleshin/django-dishka/actions/workflows/ci.yml)
28
+ ![Python Version](https://img.shields.io/pypi/pyversions/django-dishka)
29
+ [![License](https://img.shields.io/github/license/s-aleshin/django-dishka)](https://github.com/s-aleshin/django-dishka/blob/main/LICENSE)
30
+ ![Version](https://img.shields.io/pypi/v/django-dishka)
31
+
32
+ This package provides integration of [Dishka](https://github.com/reagento/dishka) DI framework and [Django](https://github.com/django/django), with typing, sync and async support.
33
+
34
+ ## Features
35
+
36
+ - [x] Automatic *REQUEST* scope management using middleware
37
+ - [x] `HttpRequest` available as context data in providers
38
+ - [x] Sync (WSGI) and async (ASGI) views
39
+ - [x] Function-based and class-based views
40
+ - [x] Supported frameworks:
41
+ - [x] [Django](https://github.com/django/django)
42
+ - [x] [Django REST Framework](https://github.com/encode/django-rest-framework)
43
+ - [x] [Django Ninja](https://github.com/vitalik/django-ninja)
44
+ - [x] [Django Modern REST](https://github.com/valery-barysok/django-modern-rest)
45
+
46
+ ## Installation
47
+
48
+ ```bash
49
+ pip install django-dishka
50
+ ```
51
+
52
+ ```bash
53
+ uv add django-dishka
54
+ ```
55
+
56
+ ## How to use
57
+
58
+ 1. Import
59
+
60
+ ```python
61
+ from dishka import FromDishka, Provider, Scope, provide
62
+ from django_dishka import DjangoProvider, inject, inject_sync, setup_dishka
63
+ ```
64
+
65
+ 2. Create provider. You can use `HttpRequest` as a factory parameter, it is available on *REQUEST* scope
66
+
67
+ ```python
68
+ class YourProvider(Provider):
69
+ @provide(scope=Scope.REQUEST)
70
+ def create_x(self, request: HttpRequest) -> X: ...
71
+ ```
72
+
73
+ 3. Mark handler parameters which are to be injected with `FromDishka[]` and decorate the handler with `@inject_sync` (sync) or `@inject` (async)
74
+
75
+ ```python
76
+ @inject_sync
77
+ def view(request: HttpRequest, x: FromDishka[X]) -> HttpResponse: ...
78
+
79
+
80
+ @inject
81
+ async def async_view(request: HttpRequest, x: FromDishka[X]) -> HttpResponse: ...
82
+ ```
83
+
84
+ For class-based views decorate the methods (`get`, `post`, etc.).
85
+
86
+ 4. *(optional)* Add `DishkaMiddleware` **to the end** of `MIDDLEWARE`. If you don't, `setup_dishka` will add it automatically
87
+
88
+ ```python
89
+ MIDDLEWARE = [
90
+ ...,
91
+ "django_dishka.DishkaMiddleware",
92
+ ]
93
+ ```
94
+
95
+ 5. Create container and setup `dishka` integration. Use `DjangoProvider()` if you are going to use `HttpRequest` in providers
96
+
97
+ ```python
98
+ # wsgi.py
99
+ container = make_container(YourProvider(), DjangoProvider())
100
+ application = setup_dishka(container, get_wsgi_application())
101
+ ```
102
+
103
+ ```python
104
+ # asgi.py
105
+ container = make_async_container(YourProvider(), DjangoProvider())
106
+ application = setup_dishka(container, get_asgi_application())
107
+ ```
108
+
109
+ ## Examples
110
+
111
+ Check [src/examples](src/examples) for examples with Django, DRF, Ninja and django-modern-rest.
112
+
113
+ ## Development
114
+
115
+ ```bash
116
+ uv sync --locked
117
+ uvx pre-commit install
118
+ uv run ruff check . && uv run ruff format --check .
119
+ uv run mypy src/django_dishka
120
+ uv run pytest # with coverage
121
+ uv build
122
+ ```
@@ -0,0 +1,98 @@
1
+ # Django integration for Dishka
2
+
3
+ [![CI](https://github.com/s-aleshin/django-dishka/actions/workflows/ci.yml/badge.svg?event=push)](https://github.com/s-aleshin/django-dishka/actions/workflows/ci.yml)
4
+ ![Python Version](https://img.shields.io/pypi/pyversions/django-dishka)
5
+ [![License](https://img.shields.io/github/license/s-aleshin/django-dishka)](https://github.com/s-aleshin/django-dishka/blob/main/LICENSE)
6
+ ![Version](https://img.shields.io/pypi/v/django-dishka)
7
+
8
+ This package provides integration of [Dishka](https://github.com/reagento/dishka) DI framework and [Django](https://github.com/django/django), with typing, sync and async support.
9
+
10
+ ## Features
11
+
12
+ - [x] Automatic *REQUEST* scope management using middleware
13
+ - [x] `HttpRequest` available as context data in providers
14
+ - [x] Sync (WSGI) and async (ASGI) views
15
+ - [x] Function-based and class-based views
16
+ - [x] Supported frameworks:
17
+ - [x] [Django](https://github.com/django/django)
18
+ - [x] [Django REST Framework](https://github.com/encode/django-rest-framework)
19
+ - [x] [Django Ninja](https://github.com/vitalik/django-ninja)
20
+ - [x] [Django Modern REST](https://github.com/valery-barysok/django-modern-rest)
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ pip install django-dishka
26
+ ```
27
+
28
+ ```bash
29
+ uv add django-dishka
30
+ ```
31
+
32
+ ## How to use
33
+
34
+ 1. Import
35
+
36
+ ```python
37
+ from dishka import FromDishka, Provider, Scope, provide
38
+ from django_dishka import DjangoProvider, inject, inject_sync, setup_dishka
39
+ ```
40
+
41
+ 2. Create provider. You can use `HttpRequest` as a factory parameter, it is available on *REQUEST* scope
42
+
43
+ ```python
44
+ class YourProvider(Provider):
45
+ @provide(scope=Scope.REQUEST)
46
+ def create_x(self, request: HttpRequest) -> X: ...
47
+ ```
48
+
49
+ 3. Mark handler parameters which are to be injected with `FromDishka[]` and decorate the handler with `@inject_sync` (sync) or `@inject` (async)
50
+
51
+ ```python
52
+ @inject_sync
53
+ def view(request: HttpRequest, x: FromDishka[X]) -> HttpResponse: ...
54
+
55
+
56
+ @inject
57
+ async def async_view(request: HttpRequest, x: FromDishka[X]) -> HttpResponse: ...
58
+ ```
59
+
60
+ For class-based views decorate the methods (`get`, `post`, etc.).
61
+
62
+ 4. *(optional)* Add `DishkaMiddleware` **to the end** of `MIDDLEWARE`. If you don't, `setup_dishka` will add it automatically
63
+
64
+ ```python
65
+ MIDDLEWARE = [
66
+ ...,
67
+ "django_dishka.DishkaMiddleware",
68
+ ]
69
+ ```
70
+
71
+ 5. Create container and setup `dishka` integration. Use `DjangoProvider()` if you are going to use `HttpRequest` in providers
72
+
73
+ ```python
74
+ # wsgi.py
75
+ container = make_container(YourProvider(), DjangoProvider())
76
+ application = setup_dishka(container, get_wsgi_application())
77
+ ```
78
+
79
+ ```python
80
+ # asgi.py
81
+ container = make_async_container(YourProvider(), DjangoProvider())
82
+ application = setup_dishka(container, get_asgi_application())
83
+ ```
84
+
85
+ ## Examples
86
+
87
+ Check [src/examples](src/examples) for examples with Django, DRF, Ninja and django-modern-rest.
88
+
89
+ ## Development
90
+
91
+ ```bash
92
+ uv sync --locked
93
+ uvx pre-commit install
94
+ uv run ruff check . && uv run ruff format --check .
95
+ uv run mypy src/django_dishka
96
+ uv run pytest # with coverage
97
+ uv build
98
+ ```
@@ -0,0 +1,106 @@
1
+ [project]
2
+ name = "django-dishka"
3
+ version = "0.1.0"
4
+ description = "Dishka dependency injection integration for Django, Django REST Framework, Django Ninja, and Django Modern Rest."
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ dependencies = [
10
+ "dishka>=1.10.1",
11
+ "django>=5",
12
+ ]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Framework :: Django",
16
+ "Intended Audience :: Developers",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Programming Language :: Python :: 3.14",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ "Typing :: Typed",
24
+ ]
25
+ keywords = [
26
+ "django",
27
+ "dishka",
28
+ "dependency injection",
29
+ "di",
30
+ "ioc",
31
+ "django-rest-framework",
32
+ "drf",
33
+ "django-ninja",
34
+ "django-modern-rest",
35
+ "dmr",
36
+ "async",
37
+ ]
38
+
39
+ [[project.authors]]
40
+ name = "Sergei Aleshin"
41
+ email = "formats_trinket7c@icloud.com"
42
+
43
+ [build-system]
44
+ requires = ["uv_build>=0.13.0,<0.14.0"]
45
+ build-backend = "uv_build"
46
+
47
+ [tool.flake8]
48
+ format = "wemake"
49
+ max-line-complexity = 16
50
+ max-try-body-length = 2
51
+ select = ["WPS"]
52
+ ignore = [
53
+ "C",
54
+ "D",
55
+ "E",
56
+ "F",
57
+ "DAR",
58
+ "RST",
59
+ "Q",
60
+ "I",
61
+ "S",
62
+ "W503",
63
+ "WPS110",
64
+ "WPS123",
65
+ "WPS201",
66
+ "WPS237",
67
+ "WPS300",
68
+ "WPS305",
69
+ "WPS306",
70
+ "WPS332",
71
+ "WPS348",
72
+ "WPS410",
73
+ "WPS412",
74
+ "WPS430",
75
+ "WPS476",
76
+ "WPS602",
77
+ "WPS604",
78
+ "WPS605",
79
+ ]
80
+ per-file-ignores = [
81
+ "src/django_dishka/integration.py: WPS111, WPS202, WPS221, WPS347, WPS421, WPS501",
82
+ "tests/*.py: WPS202, WPS221",
83
+ "settings.py: WPS226, WPS407",
84
+ ]
85
+
86
+ [tool.mypy]
87
+ files = "src/django_dishka"
88
+ strict = true
89
+ strict_bytes = true
90
+ local_partial_types = true
91
+
92
+ [dependency-groups]
93
+ dev = [
94
+ "django-modern-rest[msgspec]>=0.17.0",
95
+ "django-ninja>=1.8.0",
96
+ "django-stubs>=5",
97
+ "djangorestframework>=3.17",
98
+ "mypy>=2.4.1",
99
+ "nox>=2025.5.1",
100
+ "pytest>=8.4.0",
101
+ "pytest-asyncio>=1.5.0",
102
+ "pytest-cov>=7.1.0",
103
+ "pytest-django>=4.14.0",
104
+ "ruff>=0.17.6",
105
+ "uvicorn>=0.30.0",
106
+ ]
@@ -0,0 +1,86 @@
1
+ [project]
2
+ name = "django-dishka"
3
+ version = "0.1.0"
4
+ description = "Dishka dependency injection integration for Django, Django REST Framework, Django Ninja, and Django Modern Rest."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Sergei Aleshin", email = "formats_trinket7c@icloud.com" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ dependencies = [
13
+ "dishka>=1.10.1",
14
+ "django>=5",
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Framework :: Django",
19
+ "Intended Audience :: Developers",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Programming Language :: Python :: 3.14",
25
+ "Topic :: Software Development :: Libraries :: Python Modules",
26
+ "Typing :: Typed",
27
+ ]
28
+ keywords = [
29
+ "django",
30
+ "dishka",
31
+ "dependency injection",
32
+ "di",
33
+ "ioc",
34
+ "django-rest-framework",
35
+ "drf",
36
+ "django-ninja",
37
+ "django-modern-rest",
38
+ "dmr",
39
+ "async",
40
+ ]
41
+
42
+ [build-system]
43
+ requires = ["uv_build>=0.13.0,<0.14.0"]
44
+ build-backend = "uv_build"
45
+
46
+ [tool.flake8]
47
+ format = "wemake"
48
+ max-line-complexity = 16
49
+ max-try-body-length = 2
50
+ select = ["WPS"]
51
+
52
+ ignore = [
53
+ "C", "D", "E", "F", "DAR", "RST", "Q", "I", "S", "W503",
54
+ "WPS110", "WPS123",
55
+ "WPS201", "WPS237",
56
+ "WPS300", "WPS305", "WPS306", "WPS332", "WPS348",
57
+ "WPS410", "WPS412", "WPS430", "WPS476",
58
+ "WPS602", "WPS604", "WPS605", ]
59
+
60
+ per-file-ignores = [
61
+ "src/django_dishka/integration.py: WPS111, WPS202, WPS221, WPS347, WPS421, WPS501",
62
+ "tests/*.py: WPS202, WPS221",
63
+ "settings.py: WPS226, WPS407",
64
+ ]
65
+
66
+ [dependency-groups]
67
+ dev = [
68
+ "django-modern-rest[msgspec]>=0.17.0",
69
+ "django-ninja>=1.8.0",
70
+ "django-stubs>=5",
71
+ "djangorestframework>=3.17",
72
+ "mypy>=2.4.1",
73
+ "nox>=2025.5.1",
74
+ "pytest>=8.4.0",
75
+ "pytest-asyncio>=1.5.0",
76
+ "pytest-cov>=7.1.0",
77
+ "pytest-django>=4.14.0",
78
+ "ruff>=0.17.6",
79
+ "uvicorn>=0.30.0",
80
+ ]
81
+
82
+ [tool.mypy]
83
+ files = "src/django_dishka"
84
+ strict = true
85
+ strict_bytes = true
86
+ local_partial_types = true
@@ -0,0 +1,18 @@
1
+ from .integration import (
2
+ ROOT_CONTAINER_KEY,
3
+ DishkaMiddleware,
4
+ DjangoProvider,
5
+ inject,
6
+ inject_sync,
7
+ setup_dishka,
8
+ )
9
+
10
+
11
+ __all__ = (
12
+ "ROOT_CONTAINER_KEY",
13
+ "DishkaMiddleware",
14
+ "DjangoProvider",
15
+ "inject",
16
+ "inject_sync",
17
+ "setup_dishka",
18
+ )
@@ -0,0 +1,177 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ __all__ = (
5
+ "ROOT_CONTAINER_KEY",
6
+ "DishkaMiddleware",
7
+ "DjangoProvider",
8
+ "inject",
9
+ "inject_sync",
10
+ "setup_dishka",
11
+ )
12
+
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Any,
16
+ cast,
17
+ overload,
18
+ )
19
+
20
+ from dishka import AsyncContainer, Container, Provider, Scope, from_context
21
+ from dishka.integrations.base import wrap_injection
22
+ from django.conf import settings
23
+ from django.core.exceptions import ImproperlyConfigured
24
+ from django.core.handlers.asgi import ASGIHandler, ASGIRequest
25
+ from django.core.handlers.wsgi import WSGIHandler
26
+ from django.http import HttpRequest, HttpResponseBase
27
+ from django.utils.deprecation import MiddlewareMixin
28
+ from django.views import View
29
+
30
+
31
+ if TYPE_CHECKING:
32
+ from collections.abc import Awaitable, Callable, Iterable
33
+
34
+ from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment
35
+ from asgiref.typing import (
36
+ ASGI3Application,
37
+ ASGIReceiveCallable,
38
+ ASGISendCallable,
39
+ HTTPScope,
40
+ Scope as ASGIScope,
41
+ )
42
+
43
+
44
+ type AnyContainerT = Container | AsyncContainer
45
+ type ApplicationT = WSGIApplication | ASGI3Application
46
+ type ResponseT = HttpResponseBase | Awaitable[HttpResponseBase]
47
+
48
+ ROOT_CONTAINER_KEY = "dishka_container"
49
+ _MIDDLEWARE_PATH = "django_dishka.DishkaMiddleware"
50
+ _REQUEST_CONTAINER_ATTR = "_dishka_request_container"
51
+
52
+
53
+ class DjangoProvider(Provider):
54
+ request = from_context(HttpRequest, scope=Scope.REQUEST)
55
+
56
+
57
+ def inject_sync[**P, T](func: Callable[P, T]) -> Callable[P, T]:
58
+ return wrap_injection(
59
+ func=func,
60
+ is_async=False,
61
+ container_getter=lambda args, __: _get_request_container(args, Container),
62
+ )
63
+
64
+
65
+ def inject[**P, T](func: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]:
66
+ return wrap_injection(
67
+ func=func,
68
+ is_async=True,
69
+ container_getter=lambda args, __: _get_request_container(args, AsyncContainer),
70
+ )
71
+
72
+
73
+ class DishkaMiddleware(MiddlewareMixin):
74
+ def __call__(self, request: HttpRequest) -> ResponseT:
75
+ if self.async_mode:
76
+ return self.__acall__(request)
77
+
78
+ root = self._root_container(request, Container)
79
+ with root({HttpRequest: request}, scope=Scope.REQUEST) as container:
80
+ setattr(request, _REQUEST_CONTAINER_ATTR, container)
81
+ try:
82
+ return self.get_response(request)
83
+ finally:
84
+ delattr(request, _REQUEST_CONTAINER_ATTR)
85
+
86
+ async def __acall__(self, request: HttpRequest) -> HttpResponseBase:
87
+ root = self._root_container(request, AsyncContainer)
88
+ async with root({HttpRequest: request}, scope=Scope.REQUEST) as container:
89
+ setattr(request, _REQUEST_CONTAINER_ATTR, container)
90
+ try:
91
+ return await cast("Awaitable[HttpResponseBase]", self.get_response(request))
92
+ finally:
93
+ delattr(request, _REQUEST_CONTAINER_ATTR)
94
+
95
+ def _root_container[ContainerT: AnyContainerT](
96
+ self,
97
+ request: HttpRequest,
98
+ expected_type: type[ContainerT],
99
+ ) -> ContainerT:
100
+ context = request.scope if isinstance(request, ASGIRequest) else request.META
101
+ container = cast("dict[str, Any]", context).get(ROOT_CONTAINER_KEY)
102
+ if not isinstance(container, expected_type):
103
+ msg = (
104
+ f"{self.__class__.__name__} expected a root {expected_type.__name__}. "
105
+ "Wrap the application with setup_dishka() and register "
106
+ f"{self.__class__.__name__} last in MIDDLEWARE."
107
+ )
108
+ raise ImproperlyConfigured(msg)
109
+ return container
110
+
111
+
112
+ @overload
113
+ def setup_dishka(container: Container, app: WSGIHandler) -> WSGIApplication: ...
114
+
115
+
116
+ @overload
117
+ def setup_dishka(container: AsyncContainer, app: ASGIHandler) -> ASGI3Application: ...
118
+
119
+
120
+ def setup_dishka(
121
+ container: AnyContainerT,
122
+ app: WSGIHandler | ASGIHandler,
123
+ ) -> ApplicationT:
124
+ if container.scope is not Scope.APP:
125
+ msg = "setup_dishka() requires a container at Scope.APP."
126
+ raise ValueError(msg)
127
+
128
+ if settings.MIDDLEWARE[-1] != _MIDDLEWARE_PATH:
129
+ settings.MIDDLEWARE.append(_MIDDLEWARE_PATH)
130
+
131
+ match container, app:
132
+ case Container(), WSGIHandler():
133
+ return _wrap_wsgi(container, app)
134
+ case AsyncContainer(), ASGIHandler():
135
+ return _wrap_asgi(container, app)
136
+ case _:
137
+ msg = "Use Container with WSGIHandler or AsyncContainer with ASGIHandler."
138
+ raise TypeError(msg)
139
+
140
+
141
+ def _wrap_wsgi(container: Container, app: WSGIApplication) -> WSGIApplication:
142
+ def application(environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]:
143
+ return app({**environ, ROOT_CONTAINER_KEY: container}, start_response)
144
+
145
+ return application
146
+
147
+
148
+ def _wrap_asgi(container: AsyncContainer, handler: ASGIHandler) -> ASGI3Application:
149
+ async def application(scope: ASGIScope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
150
+ if scope["type"] == "http":
151
+ scope = cast("HTTPScope", {**scope, ROOT_CONTAINER_KEY: container})
152
+
153
+ app = cast("ASGI3Application", cast("object", handler))
154
+ await app(scope, receive, send)
155
+
156
+ return application
157
+
158
+
159
+ def _get_request_container[ContainerT: AnyContainerT](
160
+ args: tuple[object, ...],
161
+ expected_type: type[ContainerT],
162
+ ) -> ContainerT:
163
+ match args:
164
+ case (View(request=request), *_) | (request, *_):
165
+ container = getattr(request, _REQUEST_CONTAINER_ATTR, None)
166
+ case _:
167
+ container = None
168
+
169
+ if container is None:
170
+ msg = "No active Dishka request scope. Ensure the view runs inside DishkaMiddleware."
171
+ raise RuntimeError(msg)
172
+
173
+ if not isinstance(container, expected_type):
174
+ msg = f"Expected {expected_type.__name__}, got {type(container).__name__}."
175
+ raise TypeError(msg)
176
+
177
+ return container
File without changes