django-resonant-utils 0.14.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,129 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .env
106
+ .venv
107
+ env/
108
+ venv/
109
+ ENV/
110
+ env.bak/
111
+ venv.bak/
112
+
113
+ # Spyder project settings
114
+ .spyderproject
115
+ .spyproject
116
+
117
+ # Rope project settings
118
+ .ropeproject
119
+
120
+ # mkdocs documentation
121
+ /site
122
+
123
+ # mypy
124
+ .mypy_cache/
125
+ .dmypy.json
126
+ dmypy.json
127
+
128
+ # Pyre type checker
129
+ .pyre/
@@ -0,0 +1,201 @@
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,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.3
2
+ Name: django-resonant-utils
3
+ Version: 0.14.0
4
+ Summary: Django utilities for data management applications.
5
+ Project-URL: Repository, https://github.com/kitware-resonant/django-resonant-utils
6
+ Project-URL: Bug Reports, https://github.com/kitware-resonant/django-resonant-utils/issues
7
+ Maintainer-email: "Kitware, Inc." <kitware@kitware.com>
8
+ License: Apache 2.0
9
+ License-File: LICENSE
10
+ Keywords: django,resonant
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: Django
14
+ Classifier: Framework :: Django :: 4
15
+ Classifier: Framework :: Django :: 4.2
16
+ Classifier: Framework :: Django :: 5.0
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: License :: OSI Approved :: Apache Software License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: django>=4.2
27
+ Provides-Extra: allauth
28
+ Requires-Dist: django-allauth; extra == 'allauth'
29
+ Provides-Extra: minio-storage
30
+ Requires-Dist: django-minio-storage; extra == 'minio-storage'
31
+ Provides-Extra: rest-framework
32
+ Requires-Dist: djangorestframework; extra == 'rest-framework'
33
+ Provides-Extra: s3-storage
34
+ Requires-Dist: django-storages[s3]>=1.14; extra == 's3-storage'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # django-resonant-utils
38
+ [![PyPI](https://img.shields.io/pypi/v/django-resonant-utils)](https://pypi.org/project/django-resonant-utils/)
39
+
40
+ Django utilities for data management applications.
@@ -0,0 +1,4 @@
1
+ # django-resonant-utils
2
+ [![PyPI](https://img.shields.io/pypi/v/django-resonant-utils)](https://pypi.org/project/django-resonant-utils/)
3
+
4
+ Django utilities for data management applications.
@@ -0,0 +1,83 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "django-resonant-utils"
7
+ description = "Django utilities for data management applications."
8
+ readme = "README.md"
9
+ requires-python = ">=3.10"
10
+ license = { text = "Apache 2.0" }
11
+ maintainers = [{ name = "Kitware, Inc.", email = "kitware@kitware.com" }]
12
+ keywords = [
13
+ "django",
14
+ "resonant",
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Environment :: Web Environment",
19
+ 'Framework :: Django :: 4',
20
+ "Framework :: Django :: 4.2",
21
+ "Framework :: Django :: 5.0",
22
+ "Framework :: Django",
23
+ "Intended Audience :: Developers",
24
+ "License :: OSI Approved :: Apache Software License",
25
+ "Operating System :: OS Independent",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3.10",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ "Programming Language :: Python",
31
+ ]
32
+ dependencies = [
33
+ "django>=4.2",
34
+ ]
35
+ dynamic = ["version"]
36
+
37
+ [project.urls]
38
+ Repository = "https://github.com/kitware-resonant/django-resonant-utils"
39
+ "Bug Reports" = "https://github.com/kitware-resonant/django-resonant-utils/issues"
40
+
41
+ [project.optional-dependencies]
42
+ allauth = [
43
+ "django-allauth",
44
+ ]
45
+ rest_framework = [
46
+ "djangorestframework",
47
+ ]
48
+ minio_storage = [
49
+ "django-minio-storage",
50
+ ]
51
+ s3_storage = [
52
+ "django-storages[s3]>=1.14",
53
+ ]
54
+
55
+ [tool.hatch.build]
56
+ only-include = [
57
+ "resonant_utils",
58
+ ]
59
+
60
+ [tool.hatch.version]
61
+ source = "vcs"
62
+
63
+ [tool.black]
64
+ line-length = 100
65
+ target-version = ["py310"]
66
+
67
+ [tool.isort]
68
+ profile = "black"
69
+ line_length = 100
70
+ # Sort by name, don't cluster "from" vs "import"
71
+ force_sort_within_sections = true
72
+ # Combines "as" imports on the same line
73
+ combine_as_imports = true
74
+
75
+ [tool.mypy]
76
+ files = [
77
+ "resonant_utils",
78
+ ]
79
+ show_error_codes = true
80
+ strict = true
81
+ mypy_path = [
82
+ "$MYPY_CONFIG_FILE_DIR/stubs",
83
+ ]
@@ -0,0 +1,3 @@
1
+ from importlib.metadata import version
2
+
3
+ __version__ = version("django-resonant-utils")
@@ -0,0 +1,59 @@
1
+ from collections.abc import Callable
2
+ import itertools
3
+ from typing import TYPE_CHECKING, Generic, TypeVar
4
+
5
+ from django.contrib import admin
6
+ from django.contrib.admin.options import InlineModelAdmin
7
+ from django.db.models import Model
8
+ from django.http import HttpRequest
9
+
10
+ _ChildModelT = TypeVar("_ChildModelT", bound=Model)
11
+ _ParentModelT = TypeVar("_ParentModelT", bound=Model)
12
+
13
+ # https://mypy.readthedocs.io/en/latest/runtime_troubles.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime
14
+ if TYPE_CHECKING:
15
+
16
+ class _InlineMixin(InlineModelAdmin[_ChildModelT, _ParentModelT]):
17
+ pass
18
+
19
+ class _TabularInline(admin.TabularInline[_ChildModelT, _ParentModelT]):
20
+ pass
21
+
22
+ else:
23
+
24
+ class _InlineMixin(Generic[_ChildModelT, _ParentModelT]):
25
+ pass
26
+
27
+ class _TabularInline(Generic[_ChildModelT, _ParentModelT], admin.TabularInline):
28
+ pass
29
+
30
+
31
+ class ReadonlyInlineMixin(_InlineMixin[_ChildModelT, _ParentModelT]):
32
+ can_delete = False
33
+ show_change_link = True
34
+ view_on_site: bool | Callable[[_ChildModelT], str] = False
35
+ extra = 0
36
+
37
+ def get_readonly_fields(
38
+ self, request: HttpRequest, obj: _ChildModelT | None = None
39
+ ) -> list[str]:
40
+ if self.fields is None:
41
+ return []
42
+ # Make all fields readonly
43
+ # self.fields can contain nested sequences, but get_readonly_fields must return flattened
44
+ return list(
45
+ itertools.chain.from_iterable(
46
+ [field_group] if isinstance(field_group, str) else field_group
47
+ for field_group in self.fields
48
+ )
49
+ )
50
+
51
+ def has_add_permission(self, request: HttpRequest, obj: _ParentModelT | None = None) -> bool:
52
+ return False
53
+
54
+
55
+ class ReadonlyTabularInline(
56
+ ReadonlyInlineMixin[_ChildModelT, _ParentModelT],
57
+ _TabularInline[_ChildModelT, _ParentModelT],
58
+ ):
59
+ pass
@@ -0,0 +1,45 @@
1
+ from django import forms
2
+ from django.contrib.auth.models import AbstractUser
3
+ from django.http import HttpRequest
4
+ from django.utils.translation import gettext_lazy as _
5
+
6
+
7
+ # Django-Allauth further inherits from this form, and adds the typical "username", "email", etc.
8
+ # fields.
9
+ class FullNameSignupForm(forms.Form):
10
+ """
11
+ A Django-Allauth signup form which prompts for a user's first and last name.
12
+
13
+ To use this, set the setting:
14
+ ACCOUNT_SIGNUP_FORM_CLASS = 'resonant_utils.allauth.FullNameSignupForm'
15
+ """
16
+
17
+ first_name = forms.CharField(
18
+ max_length=150,
19
+ label=_("First name"),
20
+ widget=forms.TextInput(
21
+ attrs={"placeholder": _("First name"), "autocomplete": "given-name"}
22
+ ),
23
+ )
24
+ last_name = forms.CharField(
25
+ max_length=150,
26
+ label=_("Last name"),
27
+ widget=forms.TextInput(
28
+ attrs={"placeholder": _("Last name"), "auto complete": "family-name"}
29
+ ),
30
+ )
31
+
32
+ field_order = [
33
+ # Any undefined fields in this list are just ignored
34
+ "first_name",
35
+ "last_name",
36
+ "email",
37
+ "email2",
38
+ "username",
39
+ "password1",
40
+ "password2",
41
+ ]
42
+
43
+ def signup(self, request: HttpRequest, user: AbstractUser) -> None:
44
+ # Allauth requires this method to be defined
45
+ pass
@@ -0,0 +1,5 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class ResonantUtilsConfig(AppConfig):
5
+ name = "resonant_utils"
@@ -0,0 +1,86 @@
1
+ from collections.abc import Sequence
2
+ import json
3
+ from typing import Any, TypeVar
4
+
5
+ from django.core.exceptions import ValidationError
6
+ from django.db import models
7
+ from django.db.models import Manager, Model, QuerySet
8
+ from django.utils.translation import gettext_lazy as _
9
+
10
+ _T = TypeVar("_T", bound=Model, covariant=True)
11
+
12
+
13
+ class JSONObjectField(models.JSONField):
14
+ """
15
+ A field for storing JSON Objects.
16
+
17
+ Other JSON types are not allowed at the top level.
18
+ """
19
+
20
+ @staticmethod
21
+ def _validate_is_object(val: Any) -> None:
22
+ """Validate that the value is a JSON Object (dict) at the top level."""
23
+ if not isinstance(val, dict):
24
+ raise ValidationError(_("Must be a JSON Object."))
25
+
26
+ empty_values: list[Any] = [{}]
27
+
28
+ # At this point in the class definition lifecycle,
29
+ # staticmethods aren't resolvable directly, so use "__func__"
30
+ # https://stackoverflow.com/questions/41921255/staticmethod-object-is-not-callable
31
+ # Additionally, MyPy has a bug here: https://github.com/python/mypy/issues/3482
32
+ default_validators = [_validate_is_object.__func__] # type: ignore[attr-defined]
33
+
34
+ def __init__(
35
+ self,
36
+ verbose_name: str | None = None,
37
+ name: str | None = None,
38
+ encoder: type[json.JSONEncoder] | None = None,
39
+ decoder: type[json.JSONDecoder] | None = None,
40
+ **kwargs: Any,
41
+ ) -> None:
42
+ kwargs["default"] = dict
43
+ kwargs["blank"] = True
44
+ super().__init__(
45
+ verbose_name=verbose_name, name=name, encoder=encoder, decoder=decoder, **kwargs
46
+ )
47
+
48
+ def deconstruct(self) -> tuple[str, str, Sequence[Any], dict[str, Any]]:
49
+ name, path, args, kwargs = super().deconstruct()
50
+ del kwargs["default"]
51
+ del kwargs["blank"]
52
+ return name, path, args, kwargs
53
+
54
+
55
+ class SelectRelatedManager(Manager[_T]):
56
+ """
57
+ A Manager which always follows specified foreign-key relationships.
58
+
59
+ For Models which very frequently need to follow foreign-key relationships
60
+ (e.g. to generate their own __str__), it may be best to make this the
61
+ "_default_manager", so many automatically generated queries are more
62
+ efficient. To do so, define a custom "objects" as the first
63
+ Manager in the Model:
64
+ objects = SelectRelatedManager('foreign_thing')
65
+
66
+ Passing no arguments makes this follow all the Model's non-null
67
+ foreign-key relationships.
68
+ """
69
+
70
+ def __init__(self, *related_fields: str) -> None:
71
+ self.related_fields: list[str] = list(related_fields)
72
+ super().__init__()
73
+
74
+ def get_queryset(self) -> QuerySet[_T]:
75
+ return super().get_queryset().select_related(*self.related_fields)
76
+
77
+
78
+ class DeferredFieldsManager(Manager[_T]):
79
+ """A Manager which defers loading specified fields within fetched Models."""
80
+
81
+ def __init__(self, *deferred_fields: str) -> None:
82
+ self.deferred_fields = deferred_fields
83
+ super().__init__()
84
+
85
+ def get_queryset(self) -> QuerySet[_T]:
86
+ return super().get_queryset().defer(*self.deferred_fields)
@@ -0,0 +1,46 @@
1
+ from collections.abc import Generator
2
+ from contextlib import contextmanager
3
+ from pathlib import Path, PurePath
4
+ import shutil
5
+ import tempfile
6
+
7
+ from django.core.files import File
8
+ from django.db.models.fields.files import FieldFile
9
+
10
+
11
+ @contextmanager
12
+ def field_file_to_local_path(field_file: FieldFile) -> Generator[Path, None, None]:
13
+ """
14
+ Provide a filesystem path to the content of a FieldFile.
15
+
16
+ Normally, a FieldFile is usable as a Python file-like object, as:
17
+ `with model.field.open() as file_stream:`
18
+
19
+ However, in some use cases, particularly when invoking third-party libraries,
20
+ an actual filesystem path to the content is required. This context manager
21
+ provides this as:
22
+ `with field_file_to_local_path(model.field) as file_path:`
23
+
24
+ When this context manager exists, the filesystem content and path will be
25
+ garbage collected.
26
+ """
27
+ with field_file.open("rb"):
28
+ file_obj: File[bytes] = field_file.file
29
+
30
+ if type(file_obj) is File:
31
+ # When file_obj is an actual File, (typically backed by FileSystemStorage),
32
+ # it is already at a stable path on disk.
33
+ if file_obj.name is None:
34
+ raise Exception('The File object "field_file.file" does not have a "name".')
35
+ yield Path(file_obj.name)
36
+ else:
37
+ # When file_obj is actually a subclass of File, it only provides a Python
38
+ # file-like object API. So, it must be copied to a stable path.
39
+ if field_file.name is None:
40
+ raise Exception('The FieldFile object "field_file" does not have a "name".')
41
+ field_file_basename = PurePath(field_file.name).name
42
+ with tempfile.NamedTemporaryFile("wb", suffix=field_file_basename) as dest_stream:
43
+ shutil.copyfileobj(file_obj, dest_stream)
44
+ dest_stream.flush()
45
+
46
+ yield Path(dest_stream.name)
@@ -0,0 +1,12 @@
1
+ from __future__ import annotations
2
+
3
+ from django.http.response import HttpResponseRedirectBase
4
+ from django.middleware.common import CommonMiddleware
5
+
6
+
7
+ class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
8
+ status_code = 308
9
+
10
+
11
+ class PermanentRedirectCommonMiddleware(CommonMiddleware):
12
+ response_redirect_class = HttpResponsePermanentRedirect
File without changes
@@ -0,0 +1,51 @@
1
+ from typing import Any
2
+
3
+ from rest_framework.pagination import LimitOffsetPagination
4
+ from rest_framework.request import Request
5
+ from rest_framework.response import Response
6
+
7
+
8
+ class BoundedLimitOffsetPagination(LimitOffsetPagination):
9
+ """
10
+ Pagination class that forces pagination with an upper bound.
11
+
12
+ DRF's built-in paginators such as LimitOffsetPagination will cause
13
+ your endpoints to return different structure based on whether or not
14
+ paging parameters were passed in the request. In most cases it's desirable
15
+ to force pagination on endpoints that could return large result sets.
16
+ Using this class has three benefits:
17
+
18
+ 1. It will always return responses in their paged structure, i.e. a
19
+ JSON Object with "count", and a "results" Array. This is achieved by
20
+ providing a default limit that is used if none is passed.
21
+ 2. It enforces a reasonable upper bound on page sizes. Without this, users could
22
+ circumvent the intent of pagination by simply providing a high enough limit.
23
+ 3. It adds the Link header to the response, making it easier for clients to
24
+ navigate through pages of results.
25
+
26
+ The default limit will be the value of DRF's normal PAGE_SIZE setting, or
27
+ the max limit if that is not set or falsy. The upper bound on the limit is 1000.
28
+ """
29
+
30
+ max_limit = 1000
31
+
32
+ def get_limit(self, request: Request) -> int:
33
+ return super().get_limit(request) or self.max_limit
34
+
35
+ def get_paginated_response(self, data: Any) -> Response:
36
+ response = super().get_paginated_response(data)
37
+
38
+ # Add links, per https://tools.ietf.org/html/rfc8288
39
+ links = [
40
+ # (relation_type, target)
41
+ ("prev", self.get_previous_link()),
42
+ ("next", self.get_next_link()),
43
+ ]
44
+ # Always set a Link header, even if it's empty
45
+ response["Link"] = ", ".join(
46
+ f'<{target}>; rel="{relation_type}"'
47
+ for relation_type, target in links
48
+ if target is not None
49
+ )
50
+
51
+ return response
@@ -0,0 +1,29 @@
1
+ from datetime import timedelta
2
+
3
+ from django.core.files.storage import Storage
4
+
5
+ try:
6
+ from storages.backends.s3 import S3Storage
7
+ except ImportError:
8
+ # This should only be used for type interrogation, never instantiation
9
+ S3Storage = type("FakeS3Storage", (), {}) # type: ignore[assignment,misc]
10
+ try:
11
+ from minio_storage.storage import MinioStorage
12
+ except ImportError:
13
+ # This should only be used for type interrogation, never instantiation
14
+ MinioStorage = type("FakeMinioStorage", (), {}) # type: ignore[assignment,misc]
15
+
16
+
17
+ def expiring_url(storage: Storage, name: str, expiration: timedelta) -> str:
18
+ """
19
+ Return an expiring URL to a file name on a `Storage`.
20
+
21
+ `S3Storage` and `MinioStorage` are specifically supported.
22
+ """
23
+ # Each storage backend uses a slightly different API for URL expiration
24
+ if isinstance(storage, S3Storage):
25
+ return storage.url(name, expire=int(expiration.total_seconds()))
26
+ if isinstance(storage, MinioStorage):
27
+ return storage.url(name, max_age=expiration)
28
+ # Unsupported Storage type
29
+ return storage.url(name)
@@ -0,0 +1,46 @@
1
+ from collections.abc import Mapping
2
+ import json
3
+ from typing import Any, TypeVar
4
+
5
+ from django import template
6
+
7
+ register = template.Library()
8
+
9
+
10
+ _KT = TypeVar("_KT")
11
+ _VT_co = TypeVar("_VT_co", covariant=True)
12
+
13
+
14
+ @register.filter
15
+ def getitem(value: Mapping[_KT, _VT_co], arg: _KT) -> _VT_co | None:
16
+ """
17
+ Retrieve `value[arg]` from a mapping `value`, where `arg` can be a variable.
18
+
19
+ This will return `None` if `arg` is not found. It may be useful to chain the `default_if_none`
20
+ filter after this one.
21
+
22
+ Sample usage::
23
+ {% load resonant_utils %}
24
+ {% for key in some_keys %}
25
+ {{ my_dict|getitem:key }}
26
+ {% endfor %}
27
+ """
28
+ return value.get(arg, None)
29
+
30
+
31
+ @register.filter
32
+ def pretty_json(value: Any, indent: int | None = None) -> str:
33
+ """
34
+ Convert `value` to a JSON-formatted string.
35
+
36
+ Optionally, `indent` can be specified as an positive integer number of spaces to pretty-print
37
+ indentation with; `None` (the default) will disable pretty-printing.
38
+
39
+ The output should typically be embedded within HTML an `<pre>` element.
40
+ If `indent` is specified, the output will likely contain newlines, which `<pre>` will render.
41
+
42
+ Sample usage::
43
+ {% load resonant_utils %}
44
+ <pre>{{ my_object|pretty_json:4 }}</pre>
45
+ """
46
+ return json.dumps(value, indent=indent)