drf-nested-routers 0.95.3__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.
@@ -0,0 +1,333 @@
1
+ Metadata-Version: 2.4
2
+ Name: drf-nested-routers
3
+ Version: 0.95.3
4
+ Summary: Nested resources for the Django Rest Framework
5
+ Author-email: "Alan Justino et al." <alan.justino@yahoo.com.br>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/alanjds/drf-nested-routers
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Environment :: Web Environment
10
+ Classifier: Framework :: Django
11
+ Classifier: Framework :: Django :: 4.2
12
+ Classifier: Framework :: Django :: 5.0
13
+ Classifier: Framework :: Django :: 5.1
14
+ Classifier: Framework :: Django :: 5.2
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Natural Language :: English
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Internet :: WWW/HTTP
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: djangorestframework>=3.15.0
29
+ Requires-Dist: Django>=4.2
30
+ Dynamic: license-file
31
+
32
+ **This is a work in progress. It "works for me" at www.apiregistro.com.br,
33
+ but I cannot warranty that it fully "works everywhere" yet. Join us on Gitter (below) if you need some help.**
34
+
35
+ # drf-nested-routers
36
+
37
+ [![Join the chat at https://gitter.im/alanjds/drf-nested-routers](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/alanjds/drf-nested-routers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
38
+ [![Build Status](https://github.com/alanjds/drf-nested-routers/workflows/CI/badge.svg)](https://github.com/alanjds/drf-nested-routers/actions?query=workflow%3ACI+branch%3Amaster)
39
+
40
+ This package provides routers and fields to create nested resources in the [Django Rest Framework](http://django-rest-framework.org/)
41
+
42
+ Nested resources are needed for full REST URL structure, if one resource lives inside another.
43
+
44
+ The following example is about Domains and DNS Nameservers.
45
+ There are many domains, and each domain has many nameservers. The "nameserver" resource does not
46
+ exist without a domain, so you need it "nested" inside the domain.
47
+
48
+
49
+ ## Requirements & Compatibility
50
+
51
+ - Python (3.9, 3.10, 3.11, 3.12, 3.13)
52
+ - Django (4.2, 5.0, 5.1, 5.2)
53
+ - Django REST Framework (3.14, 3.15, 3.16)
54
+
55
+ It may work with lower versions, but since the release **0.94.2** is no more tested on CI for Python 3.8 or lower.<br/>
56
+ And since **0.92.1** is no more tested on CI for Pythons 2.7 to 3.5, Django 1.11 to 2.1 or DRF 3.6 to 3.10.<br/>
57
+ Before that, the release **0.90.2** was tested also with DRF 2.4.3 up to 3.7.
58
+
59
+
60
+ ## Installation
61
+
62
+ You can install this library using pip:
63
+
64
+ ```pip install drf-nested-routers```
65
+
66
+ It is not needed to add this library in your Django project's `settings.py` file, as it does not contain any app, signal or model.
67
+
68
+ ## Quickstart
69
+
70
+ The desired URL signatures are:
71
+ ```
72
+ /domains/ <- Domains list
73
+ /domains/{pk}/ <- One domain, from {pk}
74
+ /domains/{domain_pk}/nameservers/ <- Nameservers of domain from {domain_pk}
75
+ /domains/{domain_pk}/nameservers/{pk} <- Specific nameserver from {pk}, of domain from {domain_pk}
76
+ ```
77
+
78
+ How to do it (example):
79
+ ```python
80
+ # urls.py
81
+ from rest_framework_nested import routers
82
+ from views import DomainViewSet, NameserverViewSet
83
+ (...)
84
+
85
+ router = routers.SimpleRouter()
86
+ router.register(r'domains', DomainViewSet)
87
+
88
+ domains_router = routers.NestedSimpleRouter(router, r'domains', lookup='domain')
89
+ domains_router.register(r'nameservers', NameserverViewSet, basename='domain-nameservers')
90
+ # 'basename' is optional. Needed only if the same viewset is registered more than once
91
+ # Official DRF docs on this option: http://www.django-rest-framework.org/api-guide/routers/
92
+
93
+ urlpatterns = [
94
+ path(r'', include(router.urls)),
95
+ path(r'', include(domains_router.urls)),
96
+ ]
97
+ ```
98
+
99
+ ```python
100
+ # views.py
101
+
102
+ ## For Django' ORM-based resources ##
103
+
104
+ class NameserverViewSet(viewsets.ModelViewSet):
105
+ def get_queryset(self):
106
+ return Nameserver.objects.filter(domain=self.kwargs['domain_pk'])
107
+
108
+ ## OR: non-ORM resources ##
109
+
110
+ class NameserverViewSet(viewsets.ViewSet):
111
+ def list(self, request, domain_pk=None):
112
+ nameservers = self.queryset.filter(domain=domain_pk)
113
+ (...)
114
+ return Response([...])
115
+
116
+ def retrieve(self, request, pk=None, domain_pk=None):
117
+ nameservers = self.queryset.get(pk=pk, domain=domain_pk)
118
+ (...)
119
+ return Response(serializer.data)
120
+ ```
121
+
122
+ ## Advanced
123
+
124
+ ### Hyperlinks for Nested resources
125
+
126
+ **(optional)** If you need hyperlinks for nested relations, you need a custom serializer.
127
+
128
+ There you will inform how to access the *parent* of the instance being serialized when
129
+ building the *children* URL.
130
+
131
+ In the following example, an instance of Nameserver on `/domain/{domain_pk}/nameservers/{pk}`
132
+ is being informed that the *parent* Domain should be looked up using the `domain_pk` kwarg
133
+ from the URL:
134
+ ```python
135
+ # serializers.py
136
+ # (needed only if you want hyperlinks for nested relations on API)
137
+ from rest_framework_nested.relations import NestedHyperlinkedRelatedField
138
+
139
+ class DomainSerializer(HyperlinkedModelSerializer):
140
+ class Meta:
141
+ model = Domain
142
+
143
+ nameservers = HyperlinkedIdentityField(
144
+ view_name='domain-nameservers-list',
145
+ lookup_url_kwarg='domain_pk'
146
+ # ^-- Nameserver queryset will .get(domain_pk=domain_pk)
147
+ # being this value from URL kwargs
148
+ )
149
+
150
+ ## OR ##
151
+
152
+ nameservers = NestedHyperlinkedRelatedField(
153
+ many=True,
154
+ read_only=True, # Or add a queryset
155
+ view_name='domain-nameservers-detail',
156
+ parent_lookup_kwargs={'domain_pk': 'domain__pk'}
157
+ # ^-- Nameserver queryset will .filter(domain__pk=domain_pk)
158
+ # being domain_pk (ONE underscore) value from URL kwargs
159
+ )
160
+ ```
161
+
162
+ **(optional)** If you want a little bit more control over the fields displayed for the nested relations while looking at the parent, you need a custom serializer using NestedHyperlinkedModelSerializer.
163
+ ```python
164
+ from rest_framework.serializers import HyperlinkedModelSerializer
165
+ from rest_framework_nested.serializers import NestedHyperlinkedModelSerializer
166
+
167
+ class NameserverSerializers(HyperlinkedModelSerializer):
168
+ class Meta:
169
+ model = Nameserver
170
+ fields = (...)
171
+
172
+
173
+ class DomainNameserverSerializers(NestedHyperlinkedModelSerializer):
174
+ parent_lookup_kwargs = {
175
+ 'domain_pk': 'domain__pk',
176
+ }
177
+ class Meta:
178
+ model = Nameserver
179
+ fields = ('url', ...)
180
+
181
+
182
+ class DomainSerializer(HyperlinkedModelSerializer):
183
+ class Meta:
184
+ model = Domain
185
+ fields = (..., 'nameservers')
186
+
187
+ nameservers = DomainNameserverSerializers(many=True, read_only=True)
188
+ ```
189
+
190
+ ### Infinite-depth Nesting
191
+
192
+ Example of nested router 3 levels deep.
193
+ You can use this same logic to nest routers as deep as you need.
194
+ This example ahead accomplishes the below URL patterns.
195
+ ```
196
+ /clients/
197
+ /clients/{pk}/
198
+ /clients/{client_pk}/maildrops/
199
+ /clients/{client_pk}/maildrops/{pk}/
200
+ /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/
201
+ /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/
202
+ ```
203
+
204
+ ```python
205
+ # urls.py
206
+ router = DefaultRouter()
207
+ router.register(r'clients', ClientViewSet, basename='clients')
208
+ ## generates:
209
+ # /clients/
210
+ # /clients/{pk}/
211
+
212
+ client_router = routers.NestedSimpleRouter(router, r'clients', lookup='client')
213
+ client_router.register(r'maildrops', MailDropViewSet, basename='maildrops')
214
+ ## generates:
215
+ # /clients/{client_pk}/maildrops/
216
+ # /clients/{client_pk}/maildrops/{pk}/
217
+
218
+ maildrops_router = routers.NestedSimpleRouter(client_router, r'maildrops', lookup='maildrop')
219
+ maildrops_router.register(r'recipients', MailRecipientViewSet, basename='recipients')
220
+ ## generates:
221
+ # /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/
222
+ # /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/
223
+
224
+ urlpatterns = [
225
+ path(r'', include(router.urls)),
226
+ path(r'', include(client_router.urls)),
227
+ path(r'', include(maildrops_router.urls)),
228
+ ]
229
+ ```
230
+
231
+ ```python
232
+ # views.py
233
+ class ClientViewSet(viewsets.ViewSet):
234
+ serializer_class = ClientSerializer
235
+
236
+ def list(self, request,):
237
+ queryset = Client.objects.filter()
238
+ serializer = ClientSerializer(queryset, many=True)
239
+ return Response(serializer.data)
240
+
241
+ def retrieve(self, request, pk=None):
242
+ queryset = Client.objects.filter()
243
+ client = get_object_or_404(queryset, pk=pk)
244
+ serializer = ClientSerializer(client)
245
+ return Response(serializer.data)
246
+
247
+
248
+ class MailDropViewSet(viewsets.ViewSet):
249
+ serializer_class = MailDropSerializer
250
+
251
+ def list(self, request, client_pk=None):
252
+ queryset = MailDrop.objects.filter(client=client_pk)
253
+ serializer = MailDropSerializer(queryset, many=True)
254
+ return Response(serializer.data)
255
+
256
+ def retrieve(self, request, pk=None, client_pk=None):
257
+ queryset = MailDrop.objects.filter(pk=pk, client=client_pk)
258
+ maildrop = get_object_or_404(queryset, pk=pk)
259
+ serializer = MailDropSerializer(maildrop)
260
+ return Response(serializer.data)
261
+
262
+
263
+ class MailRecipientViewSet(viewsets.ViewSet):
264
+ serializer_class = MailRecipientSerializer
265
+
266
+ def list(self, request, client_pk=None, maildrop_pk=None):
267
+ queryset = MailRecipient.objects.filter(mail_drop__client=client_pk, mail_drop=maildrop_pk)
268
+ serializer = MailRecipientSerializer(queryset, many=True)
269
+ return Response(serializer.data)
270
+
271
+ def retrieve(self, request, pk=None, client_pk=None, maildrop_pk=None):
272
+ queryset = MailRecipient.objects.filter(pk=pk, mail_drop=maildrop_pk, mail_drop__client=client_pk)
273
+ maildrop = get_object_or_404(queryset, pk=pk)
274
+ serializer = MailRecipientSerializer(maildrop)
275
+ return Response(serializer.data)
276
+ ```
277
+
278
+ ```python
279
+ # serializers.py
280
+ class ClientSerializer(HyperlinkedModelSerializer):
281
+ class Meta:
282
+ model = Client
283
+ fields = (...)
284
+
285
+
286
+ class MailDropSerializer(NestedHyperlinkedModelSerializer):
287
+ parent_lookup_kwargs = {
288
+ 'client_pk': 'client__pk',
289
+ }
290
+ class Meta:
291
+ model = MailDrop
292
+ fields = (...)
293
+
294
+
295
+ class MailRecipientSerializer(NestedHyperlinkedModelSerializer):
296
+ parent_lookup_kwargs = {
297
+ 'maildrop_pk': 'mail_drop__pk',
298
+ 'client_pk': 'mail_drop__client__pk',
299
+ }
300
+ class Meta:
301
+ model = MailRecipient
302
+ fields = (...)
303
+ ```
304
+
305
+ ## Testing
306
+
307
+ In order to get started with testing, you will need to install [tox](https://tox.readthedocs.io/en/latest/).
308
+ Once installed, you can then run one environment locally, to speed up your development cycle:
309
+
310
+ ```
311
+ $ tox -e py39-django3.1-drf3.11
312
+ ```
313
+
314
+ Once you submit a pull request, your changes will be run against many environments with GitHub Actions named CI.
315
+
316
+
317
+ ## License
318
+
319
+ This package is licensed under the Apache License, Version 2.0 (the "License");
320
+ you may not use this file except in compliance with the License.
321
+ You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
322
+ and can undestand more at http://choosealicense.com/licenses/apache/ on the
323
+ sidebar notes.
324
+
325
+ Apache Licence v2.0 is a MIT-like licence. This means, in plain English:
326
+ - It's truly open source
327
+ - You can use it as you wish, for money or not
328
+ - You can sublicence it (change the licence!!)
329
+ - This way, you can even use it on your closed-source project
330
+ As long as:
331
+ - You cannot use the authors name, logos, etc, to endorse a project
332
+ - You keep the authors copyright notices where this code got used, even on your closed-source project
333
+ (come on, even Microsoft kept BSD notices on Windows about its TCP/IP stack :P)
@@ -0,0 +1,16 @@
1
+ drf_nested_routers-0.95.3.dist-info/licenses/LICENSE,sha256=IT8EBmt-GDy6uGXVH5ugyuSmnD7q_Q3DCqSDyCMUQ0Y,10267
2
+ rest_framework_nested/__init__.py,sha256=03jKSVS_K8ER4nfE-4hJbn00xqXUTgduXAfj0XTCTIM,631
3
+ rest_framework_nested/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ rest_framework_nested/relations.py,sha256=wAYgJQ1AGO6aAtdjl5oLIJ_DxNfFH4w8fTfCU_RX7j8,4667
5
+ rest_framework_nested/routers.py,sha256=bzRxgqI0V3bWHEjQHoszFiENEf_3boxbT2d2_Nqj6K4,6299
6
+ rest_framework_nested/serializers.py,sha256=WgJ95kfAlF-XYrXpuU40a6hY4zMFFotQGyjlKcQKrGA,2408
7
+ rest_framework_nested/viewsets.py,sha256=79ioXA7J6Jb-5T2FJ8zpXfZkSfJW7PCEV7pDnBoLRZA,3637
8
+ rest_framework_nested/runtests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ rest_framework_nested/runtests/runcoverage.py,sha256=IB4K8yfZFNDC_w59xTnhDNxUaMErXwEhr9ApyJOM90c,2857
10
+ rest_framework_nested/runtests/runtests.py,sha256=6NmSYA6EDFHJKkbHyHup0LYU6wWL0qbaekU0kOYTupw,1426
11
+ rest_framework_nested/runtests/settings.py,sha256=LNHpqjqsbl8_kCLzkOsr5hJFqMRQsp8SCchAP8Mqu7Q,4869
12
+ rest_framework_nested/runtests/urls.py,sha256=o5Plc17HAneid2wZ67HGt9BY90IV3cEPtD2gLe1j6pM,156
13
+ drf_nested_routers-0.95.3.dist-info/METADATA,sha256=YH0TBcQkFWPYzZ4QVw-mi18kchkBFnZX9ZEVN4kiEEQ,11703
14
+ drf_nested_routers-0.95.3.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
15
+ drf_nested_routers-0.95.3.dist-info/top_level.txt,sha256=2ihdRjd7qIseJmmMGivm5bxs7KZeqXFrx5lYSn1Bl-w,22
16
+ drf_nested_routers-0.95.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,191 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form, made
34
+ available under the License, as indicated by a copyright notice that is included
35
+ in or attached to the work (an example is provided in the Appendix below).
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work
47
+ by the copyright owner or by an individual or Legal Entity authorized to submit
48
+ on behalf of the copyright owner. For the purposes of this definition,
49
+ "submitted" means any form of electronic, verbal, or written communication sent
50
+ to the Licensor or its representatives, including but not limited to
51
+ communication on electronic mailing lists, source code control systems, and
52
+ issue tracking systems that are managed by, or on behalf of, the Licensor for
53
+ the purpose of discussing and improving the Work, but excluding communication
54
+ that is conspicuously marked or otherwise designated in writing by the copyright
55
+ owner as "Not a Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License.
62
+
63
+ Subject to the terms and conditions of this License, each Contributor hereby
64
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65
+ irrevocable copyright license to reproduce, prepare Derivative Works of,
66
+ publicly display, publicly perform, sublicense, and distribute the Work and such
67
+ Derivative Works in Source or Object form.
68
+
69
+ 3. Grant of Patent License.
70
+
71
+ Subject to the terms and conditions of this License, each Contributor hereby
72
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73
+ irrevocable (except as stated in this section) patent license to make, have
74
+ made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75
+ such license applies only to those patent claims licensable by such Contributor
76
+ that are necessarily infringed by their Contribution(s) alone or by combination
77
+ of their Contribution(s) with the Work to which such Contribution(s) was
78
+ submitted. If You institute patent litigation against any entity (including a
79
+ cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80
+ Contribution incorporated within the Work constitutes direct or contributory
81
+ patent infringement, then any patent licenses granted to You under this License
82
+ for that Work shall terminate as of the date such litigation is filed.
83
+
84
+ 4. Redistribution.
85
+
86
+ You may reproduce and distribute copies of the Work or Derivative Works thereof
87
+ in any medium, with or without modifications, and in Source or Object form,
88
+ provided that You meet the following conditions:
89
+
90
+ You must give any other recipients of the Work or Derivative Works a copy of
91
+ this License; and
92
+ You must cause any modified files to carry prominent notices stating that You
93
+ changed the files; and
94
+ You must retain, in the Source form of any Derivative Works that You distribute,
95
+ all copyright, patent, trademark, and attribution notices from the Source form
96
+ of the Work, excluding those notices that do not pertain to any part of the
97
+ Derivative Works; and
98
+ If the Work includes a "NOTICE" text file as part of its distribution, then any
99
+ Derivative Works that You distribute must include a readable copy of the
100
+ attribution notices contained within such NOTICE file, excluding those notices
101
+ that do not pertain to any part of the Derivative Works, in at least one of the
102
+ following places: within a NOTICE text file distributed as part of the
103
+ Derivative Works; within the Source form or documentation, if provided along
104
+ with the Derivative Works; or, within a display generated by the Derivative
105
+ Works, if and wherever such third-party notices normally appear. The contents of
106
+ the NOTICE file are for informational purposes only and do not modify the
107
+ License. You may add Your own attribution notices within Derivative Works that
108
+ You distribute, alongside or as an addendum to the NOTICE text from the Work,
109
+ provided that such additional attribution notices cannot be construed as
110
+ modifying the License.
111
+ You may add Your own copyright statement to Your modifications and may provide
112
+ additional or different license terms and conditions for use, reproduction, or
113
+ distribution of Your modifications, or for any such Derivative Works as a whole,
114
+ provided Your use, reproduction, and distribution of the Work otherwise complies
115
+ with the conditions stated in this License.
116
+
117
+ 5. Submission of Contributions.
118
+
119
+ Unless You explicitly state otherwise, any Contribution intentionally submitted
120
+ for inclusion in the Work by You to the Licensor shall be under the terms and
121
+ conditions of this License, without any additional terms or conditions.
122
+ Notwithstanding the above, nothing herein shall supersede or modify the terms of
123
+ any separate license agreement you may have executed with Licensor regarding
124
+ such Contributions.
125
+
126
+ 6. Trademarks.
127
+
128
+ This License does not grant permission to use the trade names, trademarks,
129
+ service marks, or product names of the Licensor, except as required for
130
+ reasonable and customary use in describing the origin of the Work and
131
+ reproducing the content of the NOTICE file.
132
+
133
+ 7. Disclaimer of Warranty.
134
+
135
+ Unless required by applicable law or agreed to in writing, Licensor provides the
136
+ Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138
+ including, without limitation, any warranties or conditions of TITLE,
139
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140
+ solely responsible for determining the appropriateness of using or
141
+ redistributing the Work and assume any risks associated with Your exercise of
142
+ permissions under this License.
143
+
144
+ 8. Limitation of Liability.
145
+
146
+ In no event and under no legal theory, whether in tort (including negligence),
147
+ contract, or otherwise, unless required by applicable law (such as deliberate
148
+ and grossly negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable to You for damages, including any direct, indirect, special, incidental,
150
+ or consequential damages of any character arising as a result of this License or
151
+ out of the use or inability to use the Work (including but not limited to
152
+ damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153
+ any and all other commercial damages or losses), even if such Contributor has
154
+ been advised of the possibility of such damages.
155
+
156
+ 9. Accepting Warranty or Additional Liability.
157
+
158
+ While redistributing the Work or Derivative Works thereof, You may choose to
159
+ offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160
+ other liability obligations and/or rights consistent with this License. However,
161
+ in accepting such obligations, You may act only on Your own behalf and on Your
162
+ sole responsibility, not on behalf of any other Contributor, and only if You
163
+ agree to indemnify, defend, and hold each Contributor harmless for any liability
164
+ incurred by, or claims asserted against, such Contributor by reason of your
165
+ accepting any such warranty or additional liability.
166
+
167
+ END OF TERMS AND CONDITIONS
168
+
169
+ APPENDIX: How to apply the Apache License to your work
170
+
171
+ To apply the Apache License to your work, attach the following boilerplate
172
+ notice, with the fields enclosed by brackets "[]" replaced with your own
173
+ identifying information. (Don't include the brackets!) The text should be
174
+ enclosed in the appropriate comment syntax for the file format. We also
175
+ recommend that a file or class name and description of purpose be included on
176
+ the same "printed page" as the copyright notice for easier identification within
177
+ third-party archives.
178
+
179
+ Copyright 2003 Alan Justino da Silva
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1 @@
1
+ rest_framework_nested
@@ -0,0 +1,15 @@
1
+ # Copyright 2013 Alan Justino da Silva, Oscar Vilaplana, et. al.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = '0.95.3'
File without changes
@@ -0,0 +1,111 @@
1
+ """
2
+ Serializer fields that deal with relationships with nested resources.
3
+
4
+ These fields allow you to specify the style that should be used to represent
5
+ model relationships with hyperlinks.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from functools import reduce
10
+ from typing import Any, Generic, TypeVar
11
+
12
+ from django.core.exceptions import ObjectDoesNotExist
13
+ from django.db.models import Model
14
+ from rest_framework.relations import HyperlinkedRelatedField, ObjectTypeError, ObjectValueError
15
+ from rest_framework.exceptions import ValidationError
16
+ from rest_framework.request import Request
17
+
18
+
19
+ T_Model = TypeVar('T_Model', bound=Model)
20
+
21
+
22
+ class NestedHyperlinkedRelatedField(HyperlinkedRelatedField, Generic[T_Model]):
23
+ lookup_field = 'pk'
24
+ parent_lookup_kwargs = {
25
+ 'parent_pk': 'parent__pk'
26
+ }
27
+
28
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
29
+ self.parent_lookup_kwargs = kwargs.pop('parent_lookup_kwargs', self.parent_lookup_kwargs)
30
+ super().__init__(*args, **kwargs)
31
+
32
+ def get_url(self, obj: Model, view_name: str, request: Request, format: str | None) -> str | None:
33
+ """
34
+ Given an object, return the URL that hyperlinks to the object.
35
+
36
+ May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
37
+ attributes are not configured to correctly match the URL conf.
38
+ """
39
+ # Unsaved objects will not yet have a valid URL.
40
+ if hasattr(obj, 'pk') and obj.pk in (None, ''):
41
+ return None
42
+
43
+ # default lookup from rest_framework.relations.HyperlinkedRelatedField
44
+ lookup_value = getattr(obj, self.lookup_field)
45
+ kwargs = {self.lookup_url_kwarg: lookup_value}
46
+
47
+ # multi-level lookup
48
+ for parent_lookup_kwarg in list(self.parent_lookup_kwargs.keys()):
49
+ underscored_lookup = self.parent_lookup_kwargs[parent_lookup_kwarg]
50
+
51
+ # split each lookup by their __, e.g. "parent__pk" will be split into "parent" and "pk", or
52
+ # "parent__super__pk" would be split into "parent", "super" and "pk"
53
+ lookups = underscored_lookup.split('__')
54
+
55
+ try:
56
+ # use the Django ORM to lookup this value, e.g., obj.parent.pk
57
+ lookup_value = reduce(getattr, [obj] + lookups) # type: ignore[operator,arg-type]
58
+ except AttributeError:
59
+ # Not nested. Act like a standard HyperlinkedRelatedField
60
+ return super().get_url(obj, view_name, request, format)
61
+
62
+ # store the lookup_name and value in kwargs, which is later passed to the reverse method
63
+ kwargs.update({parent_lookup_kwarg: lookup_value})
64
+
65
+ return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
66
+
67
+ def get_object(self, view_name: str, view_args: list[Any], view_kwargs: dict[str, Any]) -> T_Model:
68
+ """
69
+ Return the object corresponding to a matched URL.
70
+
71
+ Takes the matched URL conf arguments, and should return an
72
+ object instance, or raise an `ObjectDoesNotExist` exception.
73
+ """
74
+ # default lookup from rest_framework.relations.HyperlinkedRelatedField
75
+ lookup_value = view_kwargs[self.lookup_url_kwarg]
76
+ kwargs = {self.lookup_url_kwarg: lookup_value}
77
+
78
+ # multi-level lookup
79
+ for parent_lookup_kwarg in list(self.parent_lookup_kwargs.keys()):
80
+ lookup_value = view_kwargs[parent_lookup_kwarg]
81
+ kwargs.update({self.parent_lookup_kwargs[parent_lookup_kwarg]: lookup_value})
82
+
83
+ queryset = self.get_queryset()
84
+ assert queryset is not None
85
+ return queryset.get(**kwargs)
86
+
87
+ def use_pk_only_optimization(self) -> bool:
88
+ return False
89
+
90
+ def to_internal_value(self, data: Any) -> T_Model:
91
+ try:
92
+ return super().to_internal_value(data)
93
+ except ValidationError as err:
94
+ if err.detail[0].code != 'no_match': # type: ignore[union-attr,index]
95
+ raise
96
+
97
+ # data is probable the lookup value, not the resource URL
98
+ try:
99
+ queryset = self.get_queryset()
100
+ assert queryset is not None
101
+ return queryset.get(**{self.lookup_field: data})
102
+ except (ObjectDoesNotExist, ObjectValueError, ObjectTypeError):
103
+ self.fail('does_not_exist')
104
+
105
+
106
+ class NestedHyperlinkedIdentityField(NestedHyperlinkedRelatedField[T_Model]):
107
+ def __init__(self, view_name: str | None = None, **kwargs: Any) -> None:
108
+ assert view_name is not None, 'The `view_name` argument is required.'
109
+ kwargs['read_only'] = True
110
+ kwargs['source'] = '*'
111
+ super().__init__(view_name=view_name, **kwargs)
@@ -0,0 +1,168 @@
1
+ """
2
+ Routers for nested resources.
3
+
4
+ Example:
5
+
6
+ # urls.py
7
+
8
+ from rest_framework_nested import routers
9
+
10
+ router = routers.SimpleRouter()
11
+ router.register(r'domains', DomainViewSet)
12
+
13
+ domains_router = routers.NestedSimpleRouter(router, r'domains', lookup='domain')
14
+ domains_router.register(r'nameservers', NameserverViewSet)
15
+
16
+ url_patterns = patterns('',
17
+ path('', include(router.urls)),
18
+ path('', include(domains_router.urls)),
19
+ )
20
+
21
+ router = routers.DefaultRouter()
22
+ router.register('users', UserViewSet, 'user')
23
+ router.register('accounts', AccountViewSet, 'account')
24
+
25
+ urlpatterns = router.urls
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import sys
31
+ import re
32
+ from typing import Any
33
+
34
+ from rest_framework.routers import DefaultRouter, SimpleRouter
35
+
36
+ if sys.version_info[0] < 3:
37
+ IDENTIFIER_REGEX = re.compile(r"^[^\d\W]\w*$")
38
+ else:
39
+ IDENTIFIER_REGEX = re.compile(r"^[^\d\W]\w*$", re.UNICODE)
40
+
41
+
42
+ class LookupMixin:
43
+ """
44
+ Deprecated.
45
+
46
+ No method override is needed since Django Rest Framework 2.4.
47
+ """
48
+
49
+
50
+ class NestedMixin:
51
+ def __init__(
52
+ self,
53
+ parent_router: SimpleRouter | DefaultRouter | NestedMixin,
54
+ parent_prefix: str,
55
+ *args: Any,
56
+ **kwargs: Any
57
+ ) -> None:
58
+ self.parent_router = parent_router
59
+ self.parent_prefix = parent_prefix
60
+ self.nest_count = getattr(parent_router, 'nest_count', 0) + 1
61
+ self.nest_prefix = kwargs.pop('lookup', f'nested_{self.nest_count}') + '_'
62
+ self.use_regex_path = kwargs.get('use_regex_path', True)
63
+
64
+ super().__init__(*args, **kwargs)
65
+
66
+ if 'trailing_slash' not in kwargs:
67
+ # Inherit trailing_slash only when not specified explicitly.
68
+ #
69
+ # drf transposes the trailing_slash argument into the actual appended value
70
+ # within the route urls. This means that, on the parent class, trailing_slash
71
+ # is either '/' or '' for the expected kwarg values True or False, respectively.
72
+ # If, however, the trailing_slash property has been further customized beyond
73
+ # those two values (for example, to add an optional slash with '/?'), we won't
74
+ # be able to set it through the kwargs.
75
+ #
76
+ # By copying the value of trailing_slash directly, we ensure that our inherited
77
+ # behavior is ALWAYS consistent with the parent. If we didn't, we might create
78
+ # a situation where the parent's trailing slash is truthy (but not '/') and
79
+ # we set our trailing slash to just '/', leading to inconsistent behavior.
80
+ self.trailing_slash = parent_router.trailing_slash # type: ignore[has-type]
81
+
82
+ parent_registry = [
83
+ registered for registered
84
+ in self.parent_router.registry # type: ignore[union-attr]
85
+ if registered[0] == self.parent_prefix
86
+ ]
87
+ try:
88
+ parent_registry_item = parent_registry[0]
89
+ parent_prefix, parent_viewset, parent_basename = parent_registry_item
90
+ except:
91
+ raise RuntimeError('parent registered resource not found')
92
+
93
+ self.check_valid_name(self.nest_prefix)
94
+
95
+ nested_routes = []
96
+ parent_lookup_regex = parent_router.get_lookup_regex(parent_viewset, self.nest_prefix) # type: ignore[union-attr]
97
+
98
+ self.parent_regex = f'{parent_prefix}/{parent_lookup_regex}/'
99
+ # If there is no parent prefix, the first part of the url is probably
100
+ # controlled by the project's urls.py and the router is in an app,
101
+ # so a slash in the beginning will (A) cause Django to give warnings
102
+ # and (B) generate URLs that will require using `//`
103
+ if not self.parent_prefix and self.parent_regex[0] == '/':
104
+ self.parent_regex = self.parent_regex[1:]
105
+ if hasattr(parent_router, 'parent_regex'):
106
+ self.parent_regex = parent_router.parent_regex + self.parent_regex
107
+
108
+ for route in self.routes: # type: ignore[has-type]
109
+ route_contents = route._asdict()
110
+
111
+ # This will get passed through .format in a little bit, so we need
112
+ # to escape it
113
+ escaped_parent_regex = self.parent_regex.replace('{', '{{').replace('}', '}}')
114
+
115
+ if self.use_regex_path:
116
+ route_contents['url'] = route.url.replace('^', '^' + escaped_parent_regex)
117
+ else:
118
+ route_contents['url'] = escaped_parent_regex + route_contents['url']
119
+
120
+ nested_routes.append(type(route)(**route_contents))
121
+
122
+ self.routes = nested_routes
123
+
124
+ def check_valid_name(self, value: str) -> None:
125
+ if IDENTIFIER_REGEX.match(value) is None:
126
+ raise ValueError(f"lookup argument '{value}' needs to be valid python identifier")
127
+
128
+
129
+ class NestedSimpleRouter(NestedMixin, SimpleRouter): # type: ignore[misc]
130
+ """ Create a NestedSimpleRouter nested within `parent_router`
131
+ Args:
132
+
133
+ parent_router: Parent router. Maybe be a SimpleRouter or another nested
134
+ router.
135
+
136
+ parent_prefix: The url prefix within parent_router under which the
137
+ routes from this router should be nested.
138
+
139
+ lookup:
140
+ The regex variable that matches an instance of the parent-resource
141
+ will be called '<lookup>_<parent-viewset.lookup_field>'
142
+ In the example above, lookup=domain and the parent viewset looks up
143
+ on 'pk' so the parent lookup regex will be 'domain_pk'.
144
+ Default: 'nested_<n>' where <n> is 1+parent_router.nest_count
145
+
146
+ """
147
+ pass
148
+
149
+
150
+ class NestedDefaultRouter(NestedMixin, DefaultRouter): # type: ignore[misc]
151
+ """ Create a NestedDefaultRouter nested within `parent_router`
152
+ Args:
153
+
154
+ parent_router: Parent router. Maybe be a DefaultRouter or another nested
155
+ router.
156
+
157
+ parent_prefix: The url prefix within parent_router under which the
158
+ routes from this router should be nested.
159
+
160
+ lookup:
161
+ The regex variable that matches an instance of the parent-resource
162
+ will be called '<lookup>_<parent-viewset.lookup_field>'
163
+ In the example above, lookup=domain and the parent viewset looks up
164
+ on 'pk' so the parent lookup regex will be 'domain_pk'.
165
+ Default: 'nested_<n>' where <n> is 1+parent_router.nest_count
166
+
167
+ """
168
+ pass
File without changes
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env python
2
+ """
3
+ Useful tool to run the test suite for rest_framework and generate a coverage report.
4
+ """
5
+
6
+ # http://ericholscher.com/blog/2009/jun/29/enable-setuppy-test-your-django-apps/
7
+ # http://www.travisswicegood.com/2010/01/17/django-virtualenv-pip-and-fabric/
8
+ # http://code.djangoproject.com/svn/django/trunk/tests/runtests.py
9
+ import os
10
+ import sys
11
+ from typing import NoReturn
12
+ from coverage import coverage
13
+
14
+ # fix sys path so we don't need to setup PYTHONPATH
15
+ sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
16
+ os.environ['DJANGO_SETTINGS_MODULE'] = 'rest_framework_nested.runtests.settings'
17
+
18
+
19
+ def main() -> NoReturn:
20
+ """Run the tests for rest_framework and generate a coverage report."""
21
+
22
+ cov = coverage()
23
+ cov.erase()
24
+ cov.start()
25
+
26
+ from django.conf import settings
27
+ from django.test.utils import get_runner
28
+ TestRunner = get_runner(settings)
29
+
30
+ failures: int
31
+ if hasattr(TestRunner, 'func_name'):
32
+ # Pre 1.2 test runners were just functions,
33
+ # and did not support the 'failfast' option.
34
+ import warnings
35
+ warnings.warn(
36
+ 'Function-based test runners are deprecated. Test runners should be classes with a run_tests() method.',
37
+ DeprecationWarning
38
+ )
39
+ failures = TestRunner(['tests']) # type: ignore[assignment,arg-type]
40
+ else:
41
+ test_runner = TestRunner()
42
+ failures = test_runner.run_tests(['tests'])
43
+ cov.stop()
44
+
45
+ # Discover the list of all modules that we should test coverage for
46
+ import rest_framework
47
+
48
+ project_dir = os.path.dirname(rest_framework.__file__)
49
+ cov_files = []
50
+
51
+ for (path, dirs, files) in os.walk(project_dir):
52
+ # Drop tests and runtests directories from the test coverage report
53
+ if os.path.basename(path) in ['tests', 'runtests', 'migrations']:
54
+ continue
55
+
56
+ # Drop the compat and six modules from coverage, since we're not interested in the coverage
57
+ # of modules which are specifically for resolving environment dependant imports.
58
+ # (Because we'll end up getting different coverage reports for it for each environment)
59
+ if 'compat.py' in files:
60
+ files.remove('compat.py')
61
+
62
+ if 'six.py' in files:
63
+ files.remove('six.py')
64
+
65
+ # Same applies to template tags module.
66
+ # This module has to include branching on Django versions,
67
+ # so it's never possible for it to have full coverage.
68
+ if 'rest_framework.py' in files:
69
+ files.remove('rest_framework.py')
70
+
71
+ cov_files.extend([os.path.join(path, file) for file in files if file.endswith('.py')])
72
+
73
+ cov.report(cov_files)
74
+ if '--html' in sys.argv:
75
+ cov.html_report(cov_files, directory='coverage')
76
+ sys.exit(failures)
77
+
78
+ if __name__ == '__main__':
79
+ import ipdb
80
+ ipdb.set_trace()
81
+ main()
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env python
2
+
3
+ # http://ericholscher.com/blog/2009/jun/29/enable-setuppy-test-your-django-apps/
4
+ # http://www.travisswicegood.com/2010/01/17/django-virtualenv-pip-and-fabric/
5
+ # http://code.djangoproject.com/svn/django/trunk/tests/runtests.py
6
+ import os
7
+ import sys
8
+ from typing import NoReturn
9
+
10
+ # fix sys path so we don't need to setup PYTHONPATH
11
+ sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
12
+ os.environ['DJANGO_SETTINGS_MODULE'] = 'rest_framework_nested.runtests.settings'
13
+
14
+ import django
15
+ from django.conf import settings
16
+ from django.test.utils import get_runner
17
+
18
+
19
+ def usage() -> str:
20
+ return """
21
+ Usage: python runtests.py [UnitTestClass].[method]
22
+
23
+ You can pass the Class name of the `UnitTestClass` you want to test.
24
+
25
+ Append a method name if you only want to test a specific method of that class.
26
+ """
27
+
28
+
29
+ def main() -> NoReturn:
30
+ TestRunner = get_runner(settings)
31
+ import ipdb
32
+ ipdb.set_trace()
33
+
34
+ test_runner = TestRunner()
35
+ if len(sys.argv) == 2:
36
+ test_case = '.' + sys.argv[1]
37
+ elif len(sys.argv) == 1:
38
+ test_case = ''
39
+ else:
40
+ print(usage())
41
+ sys.exit(1)
42
+ test_module_name = 'rest_framework_nested.tests'
43
+ if django.VERSION[0] == 1 and django.VERSION[1] < 6:
44
+ test_module_name = 'tests'
45
+
46
+ failures = test_runner.run_tests([test_module_name + test_case])
47
+
48
+ sys.exit(failures)
49
+
50
+ if __name__ == '__main__':
51
+ main()
@@ -0,0 +1,159 @@
1
+ from __future__ import annotations
2
+
3
+ # Django settings for testproject project.
4
+
5
+ DEBUG = True
6
+ TEMPLATE_DEBUG = DEBUG
7
+ DEBUG_PROPAGATE_EXCEPTIONS = True
8
+
9
+ ALLOWED_HOSTS = ['*']
10
+
11
+ ADMINS = (
12
+ # ('Your Name', 'your_email@domain.com'),
13
+ )
14
+
15
+ MANAGERS = ADMINS
16
+
17
+ DATABASES = {
18
+ 'default': {
19
+ 'ENGINE': 'django.db.backends.sqlite3', # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3', 'oracle'.
20
+ 'NAME': 'sqlite.db', # Or path to database file if using sqlite3.
21
+ 'USER': '', # Not used with sqlite3.
22
+ 'PASSWORD': '', # Not used with sqlite3.
23
+ 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
24
+ 'PORT': '', # Set to empty string for default. Not used with sqlite3.
25
+ }
26
+ }
27
+
28
+ CACHES = {
29
+ 'default': {
30
+ 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
31
+ }
32
+ }
33
+
34
+ # Local time zone for this installation. Choices can be found here:
35
+ # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
36
+ # although not all choices may be available on all operating systems.
37
+ # On Unix systems, a value of None will cause Django to use the same
38
+ # timezone as the operating system.
39
+ # If running in a Windows environment this must be set to the same as your
40
+ # system time zone.
41
+ TIME_ZONE = 'Europe/London'
42
+
43
+ # Language code for this installation. All choices can be found here:
44
+ # http://www.i18nguy.com/unicode/language-identifiers.html
45
+ LANGUAGE_CODE = 'en-uk'
46
+
47
+ SITE_ID = 1
48
+
49
+ # If you set this to False, Django will make some optimizations so as not
50
+ # to load the internationalization machinery.
51
+ USE_I18N = True
52
+
53
+ # Absolute filesystem path to the directory that will hold user-uploaded files.
54
+ # Example: "/home/media/media.lawrence.com/"
55
+ MEDIA_ROOT = ''
56
+
57
+ # URL that handles the media served from MEDIA_ROOT. Make sure to use a
58
+ # trailing slash if there is a path component (optional in other cases).
59
+ # Examples: "http://media.lawrence.com", "http://example.com/media/"
60
+ MEDIA_URL = ''
61
+
62
+ # Make this unique, and don't share it with anybody.
63
+ SECRET_KEY = 'u@x-aj9(hoh#rb-^ymf#g2jx_hp0vj7u5#b@ag1n^seu9e!%cy'
64
+
65
+ # List of callables that know how to import templates from various sources.
66
+ TEMPLATE_LOADERS = (
67
+ 'django.template.loaders.filesystem.Loader',
68
+ 'django.template.loaders.app_directories.Loader',
69
+ # 'django.template.loaders.eggs.Loader',
70
+ )
71
+
72
+ MIDDLEWARE_CLASSES = (
73
+ 'django.middleware.common.CommonMiddleware',
74
+ 'django.contrib.sessions.middleware.SessionMiddleware',
75
+ 'django.middleware.csrf.CsrfViewMiddleware',
76
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
77
+ 'django.contrib.messages.middleware.MessageMiddleware',
78
+ )
79
+
80
+ ROOT_URLCONF = 'urls'
81
+
82
+ TEMPLATE_DIRS = (
83
+ # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
84
+ # Always use forward slashes, even on Windows.
85
+ # Don't forget to use absolute paths, not relative paths.
86
+ )
87
+
88
+ INSTALLED_APPS = [
89
+ 'django.contrib.auth',
90
+ 'django.contrib.contenttypes',
91
+ 'django.contrib.sessions',
92
+ 'django.contrib.sites',
93
+ 'django.contrib.messages',
94
+ # Uncomment the next line to enable the admin:
95
+ # 'django.contrib.admin',
96
+ # Uncomment the next line to enable admin documentation:
97
+ # 'django.contrib.admindocs',
98
+ # 'rest_framework.authtoken',
99
+ 'rest_framework_nested',
100
+ 'rest_framework_nested.tests',
101
+ ]
102
+
103
+ # OAuth is optional and won't work if there is no oauth_provider & oauth2
104
+ try:
105
+ import oauth_provider # noqa: F401
106
+ import oauth2 # noqa: F401
107
+ except ImportError:
108
+ pass
109
+ else:
110
+ INSTALLED_APPS += [
111
+ 'oauth_provider',
112
+ ]
113
+
114
+ try:
115
+ import provider # noqa: F401
116
+ except ImportError:
117
+ pass
118
+ else:
119
+ INSTALLED_APPS += [
120
+ 'provider',
121
+ 'provider.oauth2',
122
+ ]
123
+
124
+ # guardian is optional
125
+ try:
126
+ import guardian # noqa: F401
127
+ except ImportError:
128
+ pass
129
+ else:
130
+ ANONYMOUS_USER_ID = -1
131
+ AUTHENTICATION_BACKENDS = (
132
+ 'django.contrib.auth.backends.ModelBackend', # default
133
+ 'guardian.backends.ObjectPermissionBackend',
134
+ )
135
+ INSTALLED_APPS += [
136
+ 'guardian',
137
+ ]
138
+
139
+ STATIC_URL = '/static/'
140
+
141
+ PASSWORD_HASHERS = (
142
+ 'django.contrib.auth.hashers.SHA1PasswordHasher',
143
+ 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
144
+ 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
145
+ 'django.contrib.auth.hashers.BCryptPasswordHasher',
146
+ 'django.contrib.auth.hashers.MD5PasswordHasher',
147
+ 'django.contrib.auth.hashers.CryptPasswordHasher',
148
+ )
149
+
150
+ AUTH_USER_MODEL = 'auth.User'
151
+
152
+ import django
153
+ # If we're running on the Jenkins server we want to archive the coverage reports as XML.
154
+ import os
155
+ if os.environ.get('HUDSON_URL', None):
156
+ TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner'
157
+ TEST_OUTPUT_VERBOSE = True
158
+ TEST_OUTPUT_DESCRIPTIONS = True
159
+ TEST_OUTPUT_DIR = 'xmlrunner'
@@ -0,0 +1,6 @@
1
+ """
2
+ Blank URLConf just to keep runtests.py happy.
3
+ """
4
+ from rest_framework.compat import patterns # type: ignore[attr-defined]
5
+
6
+ urlpatterns = patterns('',)
@@ -0,0 +1,66 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, TypeVar
4
+
5
+ import rest_framework.serializers
6
+ from django.db.models import Model
7
+ from rest_framework.fields import Field
8
+ from rest_framework.utils.model_meta import RelationInfo
9
+ from rest_framework_nested.relations import NestedHyperlinkedIdentityField, NestedHyperlinkedRelatedField
10
+ try:
11
+ from rest_framework.utils.field_mapping import get_nested_relation_kwargs
12
+ except ImportError:
13
+ pass
14
+ # passing because NestedHyperlinkedModelSerializer can't be used anyway
15
+ # if version too old.
16
+
17
+
18
+ T_Model = TypeVar('T_Model', bound=Model)
19
+
20
+
21
+ class NestedHyperlinkedModelSerializer(rest_framework.serializers.HyperlinkedModelSerializer[T_Model]):
22
+ """
23
+ A type of `ModelSerializer` that uses hyperlinked relationships with compound keys instead
24
+ of primary key relationships. Specifically:
25
+
26
+ * A 'url' field is included instead of the 'id' field.
27
+ * Relationships to other instances are hyperlinks, instead of primary keys.
28
+
29
+ NOTE: this only works with DRF 3.1.0 and above.
30
+ """
31
+ parent_lookup_kwargs = {
32
+ 'parent_pk': 'parent__pk'
33
+ }
34
+
35
+ serializer_url_field = NestedHyperlinkedIdentityField
36
+ serializer_related_field = NestedHyperlinkedRelatedField
37
+
38
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
39
+ self.parent_lookup_kwargs = kwargs.pop('parent_lookup_kwargs', self.parent_lookup_kwargs)
40
+ super().__init__(*args, **kwargs)
41
+
42
+ def build_url_field(self, field_name: str, model_class: type[T_Model]) -> tuple[type[Field], dict[str, Any]]:
43
+ field_class, field_kwargs = super().build_url_field(
44
+ field_name,
45
+ model_class
46
+ )
47
+ field_kwargs['parent_lookup_kwargs'] = self.parent_lookup_kwargs
48
+
49
+ return field_class, field_kwargs
50
+
51
+ def build_nested_field(
52
+ self, field_name: str, relation_info: RelationInfo, nested_depth: int
53
+ ) -> tuple[type[Field], dict[str, Any]]:
54
+ """
55
+ Create nested fields for forward and reverse relationships.
56
+ """
57
+ class NestedSerializer(NestedHyperlinkedModelSerializer):
58
+ class Meta:
59
+ model = relation_info.related_model
60
+ depth = nested_depth - 1
61
+ fields = '__all__'
62
+
63
+ field_class = NestedSerializer
64
+ field_kwargs = get_nested_relation_kwargs(relation_info)
65
+
66
+ return field_class, field_kwargs
@@ -0,0 +1,86 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ from typing import Any, Generic, Iterator, TypeVar
5
+
6
+ from django.core.exceptions import ImproperlyConfigured
7
+ from django.db.models import Model, QuerySet
8
+ from django.http import HttpRequest, QueryDict
9
+ from rest_framework.request import Request
10
+ from rest_framework.serializers import BaseSerializer
11
+
12
+ T_Model = TypeVar('T_Model', bound=Model)
13
+
14
+
15
+ @contextlib.contextmanager
16
+ def _force_mutable(querydict: QueryDict | dict[str, Any] | list[Any]) -> Iterator[QueryDict | dict[str, Any] | list[Any]]:
17
+ """
18
+ Takes a HttpRequest querydict from Django and forces it to be mutable.
19
+ Reverts the initial state back on exit, if any.
20
+ """
21
+ initial_mutability = getattr(querydict, '_mutable', None)
22
+ if initial_mutability is not None:
23
+ querydict._mutable = True # type: ignore[union-attr]
24
+ yield querydict
25
+ if initial_mutability is not None:
26
+ querydict._mutable = initial_mutability # type: ignore[union-attr]
27
+
28
+
29
+ class NestedViewSetMixin(Generic[T_Model]):
30
+ def _get_parent_lookup_kwargs(self) -> dict[str, str]:
31
+ """
32
+ Locates and returns the `parent_lookup_kwargs` dict informing
33
+ how the kwargs in the URL maps to the parents of the model instance
34
+
35
+ For now, fetches from `parent_lookup_kwargs`
36
+ on the ViewSet or Serializer attached. This may change on the future.
37
+ """
38
+ parent_lookup_kwargs = getattr(self, 'parent_lookup_kwargs', None)
39
+
40
+ if not parent_lookup_kwargs:
41
+ serializer_class: type[BaseSerializer[T_Model]] = self.get_serializer_class() # type: ignore[attr-defined]
42
+ parent_lookup_kwargs = getattr(serializer_class, 'parent_lookup_kwargs', None)
43
+
44
+ if not parent_lookup_kwargs:
45
+ raise ImproperlyConfigured(
46
+ "NestedViewSetMixin need 'parent_lookup_kwargs' to find the parent from the URL"
47
+ )
48
+
49
+ return parent_lookup_kwargs
50
+
51
+ def get_queryset(self) -> QuerySet[T_Model]:
52
+ """
53
+ Filter the `QuerySet` based on its parents as defined in the
54
+ `serializer_class.parent_lookup_kwargs` or `viewset.parent_lookup_kwargs`
55
+ """
56
+ queryset = super().get_queryset() # type: ignore[misc]
57
+
58
+ if getattr(self, 'swagger_fake_view', False):
59
+ return queryset
60
+
61
+ orm_filters: dict[str, Any] = {}
62
+ parent_lookup_kwargs = self._get_parent_lookup_kwargs()
63
+ for query_param, field_name in parent_lookup_kwargs.items():
64
+ orm_filters[field_name] = self.kwargs[query_param] # type: ignore[attr-defined]
65
+ return queryset.filter(**orm_filters)
66
+
67
+ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:
68
+ """
69
+ Adds the parent params from URL inside the children data available
70
+ """
71
+ # run all the DRF API policies first
72
+ super().initial(request, *args, **kwargs) # type: ignore[misc]
73
+
74
+ if getattr(self, 'swagger_fake_view', False):
75
+ return
76
+
77
+ for url_kwarg, fk_filter in self._get_parent_lookup_kwargs().items():
78
+ # fk_filter is alike 'grandparent__parent__pk'
79
+ parent_arg = fk_filter.partition('__')[0]
80
+ for querydict in [request.data, request.query_params]:
81
+ with _force_mutable(querydict):
82
+ if isinstance(querydict, list): # type: ignore[unreachable]
83
+ for querydict_item in querydict: # type: ignore[unreachable]
84
+ querydict_item[parent_arg] = kwargs[url_kwarg]
85
+ else:
86
+ querydict[parent_arg] = kwargs[url_kwarg]