django-resonant-utils 0.17.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,174 @@
1
+ # Created by https://www.toptal.com/developers/gitignore/api/django
2
+ # Edit at https://www.toptal.com/developers/gitignore?templates=django
3
+
4
+ ### Django ###
5
+ *.log
6
+ *.pot
7
+ *.pyc
8
+ __pycache__/
9
+ local_settings.py
10
+ db.sqlite3
11
+ db.sqlite3-journal
12
+ media
13
+
14
+ # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/
15
+ # in your Git repository. Update and uncomment the following line accordingly.
16
+ # <django-project-name>/staticfiles/
17
+
18
+ ### Django.Python Stack ###
19
+ # Byte-compiled / optimized / DLL files
20
+ *.py[cod]
21
+ *$py.class
22
+
23
+ # C extensions
24
+ *.so
25
+
26
+ # Distribution / packaging
27
+ .Python
28
+ build/
29
+ develop-eggs/
30
+ dist/
31
+ downloads/
32
+ eggs/
33
+ .eggs/
34
+ lib/
35
+ lib64/
36
+ parts/
37
+ sdist/
38
+ var/
39
+ wheels/
40
+ share/python-wheels/
41
+ *.egg-info/
42
+ .installed.cfg
43
+ *.egg
44
+ MANIFEST
45
+
46
+ # PyInstaller
47
+ # Usually these files are written by a python script from a template
48
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
49
+ *.manifest
50
+ *.spec
51
+
52
+ # Installer logs
53
+ pip-log.txt
54
+ pip-delete-this-directory.txt
55
+
56
+ # Unit test / coverage reports
57
+ htmlcov/
58
+ .tox/
59
+ .nox/
60
+ .coverage
61
+ .coverage.*
62
+ .cache
63
+ nosetests.xml
64
+ coverage.xml
65
+ *.cover
66
+ *.py,cover
67
+ .hypothesis/
68
+ .pytest_cache/
69
+ cover/
70
+
71
+ # Translations
72
+ *.mo
73
+
74
+ # Django stuff:
75
+
76
+ # Flask stuff:
77
+ instance/
78
+ .webassets-cache
79
+
80
+ # Scrapy stuff:
81
+ .scrapy
82
+
83
+ # Sphinx documentation
84
+ docs/_build/
85
+
86
+ # PyBuilder
87
+ .pybuilder/
88
+ target/
89
+
90
+ # Jupyter Notebook
91
+ .ipynb_checkpoints
92
+
93
+ # IPython
94
+ profile_default/
95
+ ipython_config.py
96
+
97
+ # pyenv
98
+ # For a library or package, you might want to ignore these files since the code is
99
+ # intended to run in multiple environments; otherwise, check them in:
100
+ # .python-version
101
+
102
+ # pipenv
103
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
104
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
105
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
106
+ # install all needed dependencies.
107
+ #Pipfile.lock
108
+
109
+ # poetry
110
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
111
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
112
+ # commonly ignored for libraries.
113
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
114
+ #poetry.lock
115
+
116
+ # pdm
117
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
118
+ #pdm.lock
119
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
120
+ # in version control.
121
+ # https://pdm.fming.dev/#use-with-ide
122
+ .pdm.toml
123
+
124
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
125
+ __pypackages__/
126
+
127
+ # Celery stuff
128
+ celerybeat-schedule
129
+ celerybeat.pid
130
+
131
+ # SageMath parsed files
132
+ *.sage.py
133
+
134
+ # Environments
135
+ .env
136
+ .venv
137
+ env/
138
+ venv/
139
+ ENV/
140
+ env.bak/
141
+ venv.bak/
142
+
143
+ # Spyder project settings
144
+ .spyderproject
145
+ .spyproject
146
+
147
+ # Rope project settings
148
+ .ropeproject
149
+
150
+ # mkdocs documentation
151
+ /site
152
+
153
+ # mypy
154
+ .mypy_cache/
155
+ .dmypy.json
156
+ dmypy.json
157
+
158
+ # Pyre type checker
159
+ .pyre/
160
+
161
+ # pytype static type analyzer
162
+ .pytype/
163
+
164
+ # Cython debug symbols
165
+ cython_debug/
166
+
167
+ # PyCharm
168
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
169
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
170
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
171
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
172
+ #.idea/
173
+
174
+ # End of https://www.toptal.com/developers/gitignore/api/django
@@ -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,13 @@
1
+ Copyright 2020 Kitware, Inc.
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
+ See accompanying LICENSE file. 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.
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-resonant-utils
3
+ Version: 0.17.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-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Keywords: django,kitware-resonant,resonant
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Web Environment
14
+ Classifier: Framework :: Django
15
+ Classifier: Framework :: Django :: 5
16
+ Classifier: Framework :: Django :: 5.2
17
+ Classifier: Framework :: Django :: 6
18
+ Classifier: Framework :: Django :: 6.0
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3.14
26
+ Requires-Python: >=3.12
27
+ Requires-Dist: django>=5.2
28
+ Provides-Extra: allauth
29
+ Requires-Dist: django-allauth; extra == 'allauth'
30
+ Provides-Extra: minio-storage
31
+ Requires-Dist: django-minio-storage; extra == 'minio-storage'
32
+ Provides-Extra: rest-framework
33
+ Requires-Dist: djangorestframework; extra == 'rest-framework'
34
+ Provides-Extra: s3-storage
35
+ Requires-Dist: django-storages[s3]>=1.14; extra == 's3-storage'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # django-resonant-utils
39
+ [![PyPI](https://img.shields.io/pypi/v/django-resonant-utils)](https://pypi.org/project/django-resonant-utils/)
40
+
41
+ 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,158 @@
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.12"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ maintainers = [{ name = "Kitware, Inc.", email = "kitware@kitware.com" }]
13
+ keywords = [
14
+ "django",
15
+ "resonant",
16
+ "kitware-resonant",
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Environment :: Web Environment",
21
+ "Framework :: Django",
22
+ "Framework :: Django :: 5",
23
+ "Framework :: Django :: 5.2",
24
+ "Framework :: Django :: 6",
25
+ "Framework :: Django :: 6.0",
26
+ "Intended Audience :: Developers",
27
+ "Operating System :: OS Independent",
28
+ "Programming Language :: Python",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3.12",
31
+ "Programming Language :: Python :: 3.13",
32
+ "Programming Language :: Python :: 3.14",
33
+ ]
34
+ dependencies = [
35
+ "django>=5.2",
36
+ ]
37
+ dynamic = ["version"]
38
+
39
+ [project.urls]
40
+ Repository = "https://github.com/kitware-resonant/django-resonant-utils"
41
+ "Bug Reports" = "https://github.com/kitware-resonant/django-resonant-utils/issues"
42
+
43
+ [project.optional-dependencies]
44
+ allauth = [
45
+ "django-allauth",
46
+ ]
47
+ rest_framework = [
48
+ "djangorestframework",
49
+ ]
50
+ minio_storage = [
51
+ "django-minio-storage",
52
+ ]
53
+ s3_storage = [
54
+ "django-storages[s3]>=1.14",
55
+ ]
56
+
57
+ [dependency-groups]
58
+ dev = [
59
+ "tox==4.34.1",
60
+ "tox-uv==1.29.0",
61
+ ]
62
+ lint = [
63
+ "ruff==0.14.14",
64
+ ]
65
+ type = [
66
+ "mypy==1.19.1",
67
+ "django-stubs[compatible-mypy]==5.2.9",
68
+ "djangorestframework-stubs==3.16.7",
69
+ ]
70
+
71
+ [tool.hatch.build]
72
+ only-include = [
73
+ "resonant_utils",
74
+ ]
75
+
76
+ [tool.hatch.version]
77
+ source = "vcs"
78
+
79
+ [tool.black]
80
+ line-length = 100
81
+ target-version = ["py312"]
82
+
83
+ [tool.ruff]
84
+ line-length = 100
85
+ target-version = "py313"
86
+
87
+ [tool.ruff.lint]
88
+ select = ["ALL"]
89
+ ignore = [
90
+ # Incompatible with formatter
91
+ # https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules
92
+ "COM812", # missing-trailing-comma
93
+ "COM819", # prohibited-trailing-comma
94
+ "D206", # docstring-tab-indentation
95
+ "D300", # triple-single-quotes
96
+ "E111", # indentation-with-invalid-multiple
97
+ "E114", # indentation-with-invalid-multiple-comment
98
+ "E117", # over-indented
99
+ "ISC001", # single-line-implicit-string-concatenation
100
+ "ISC002", # multi-line-implicit-string-concatenation
101
+ "Q", # flake8-quotes
102
+ "W191", # tab-indentation
103
+
104
+ # Incompatible with Django
105
+ "A003", # builtin-attribute-shadowing
106
+ "ARG001", # unused-function-argument
107
+ "ARG002", # unused-method-argument
108
+ "RUF012", # mutable-class-default
109
+
110
+ # Overly burdensome
111
+ "ANN", # flake8-annotations
112
+ "D1", # undocumented-*
113
+ "EM101", # raw-string-in-exception
114
+ "ERA001", # commented-out-code
115
+ "FIX", # flake8-fixme
116
+ "RET506", # superfluous-else-raise
117
+ "TD002", # missing-todo-author
118
+ "TD003", # missing-todo-link
119
+ "TRY003", # raise-vanilla-args
120
+
121
+ # Project-specific
122
+ ]
123
+
124
+ [tool.ruff.lint.per-file-ignores]
125
+ "**/tests/**" = [
126
+ "DJ007", # django-all-with-model-form
127
+ "DJ008", # django-model-without-dunder-str
128
+ "PLR0913", # too-many-arguments
129
+ "PLR2004", # magic-value-comparison
130
+ "S", # flake8-bandit
131
+ "SLF001", # private-member-access
132
+ ]
133
+
134
+ [tool.ruff.lint.flake8-self]
135
+ extend-ignore-names = ["_base_manager", "_default_manager", "_meta"]
136
+
137
+ [tool.ruff.lint.isort]
138
+ # Sort by name, don't cluster "from" vs "import"
139
+ force-sort-within-sections = true
140
+ # Deferred annotations allows TC* rules to move more imports into TYPE_CHECKING blocks
141
+ required-imports = ["from __future__ import annotations"]
142
+
143
+ [tool.ruff.lint.pydocstyle]
144
+ convention = "pep257"
145
+
146
+ [tool.mypy]
147
+ files = [
148
+ "resonant_utils",
149
+ ]
150
+ check_untyped_defs = true
151
+ show_error_codes = true
152
+ strict = true
153
+ warn_redundant_casts = true
154
+ warn_unused_configs = true
155
+ warn_unused_ignores = true
156
+ mypy_path = [
157
+ "$MYPY_CONFIG_FILE_DIR/stubs",
158
+ ]
@@ -0,0 +1,65 @@
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ from typing import TYPE_CHECKING
5
+
6
+ from django.contrib import admin
7
+ from django.db.models import Model
8
+
9
+ # https://mypy.readthedocs.io/en/latest/runtime_troubles.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Callable
12
+
13
+ from django.contrib.admin.options import InlineModelAdmin
14
+ from django.http import HttpRequest
15
+
16
+ class _InlineMixin[ChildModelT: Model, ParentModelT: Model](
17
+ InlineModelAdmin[ChildModelT, ParentModelT]
18
+ ):
19
+ pass
20
+
21
+ class _TabularInline[ChildModelT: Model, ParentModelT: Model](
22
+ admin.TabularInline[ChildModelT, ParentModelT]
23
+ ):
24
+ pass
25
+
26
+ else:
27
+
28
+ class _InlineMixin[ChildModelT: Model, ParentModelT: Model]:
29
+ pass
30
+
31
+ class _TabularInline[ChildModelT: Model, ParentModelT: Model](admin.TabularInline):
32
+ pass
33
+
34
+
35
+ class ReadonlyInlineMixin[ChildModelT: Model, ParentModelT: Model](
36
+ _InlineMixin[ChildModelT, ParentModelT]
37
+ ):
38
+ can_delete = False
39
+ show_change_link = True
40
+ view_on_site: bool | Callable[[ChildModelT], str] = False
41
+ extra = 0
42
+
43
+ def get_readonly_fields(
44
+ self, request: HttpRequest, obj: ChildModelT | None = None
45
+ ) -> list[str]:
46
+ if self.fields is None:
47
+ return []
48
+ # Make all fields readonly
49
+ # self.fields can contain nested sequences, but get_readonly_fields must return flattened
50
+ return list(
51
+ itertools.chain.from_iterable(
52
+ [field_group] if isinstance(field_group, str) else field_group
53
+ for field_group in self.fields
54
+ )
55
+ )
56
+
57
+ def has_add_permission(self, request: HttpRequest, obj: ParentModelT | None = None) -> bool:
58
+ return False
59
+
60
+
61
+ class ReadonlyTabularInline[ChildModelT: Model, ParentModelT: Model](
62
+ ReadonlyInlineMixin[ChildModelT, ParentModelT],
63
+ _TabularInline[ChildModelT, ParentModelT],
64
+ ):
65
+ pass
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from django import forms
6
+ from django.utils.translation import gettext_lazy as _
7
+
8
+ if TYPE_CHECKING:
9
+ from django.contrib.auth.models import AbstractUser
10
+ from django.http import HttpRequest
11
+
12
+
13
+ # Django-Allauth further inherits from this form, and adds the typical "username", "email", etc.
14
+ # fields.
15
+ class FullNameSignupForm(forms.Form):
16
+ """
17
+ A Django-Allauth signup form which prompts for a user's first and last name.
18
+
19
+ To use this, set the setting:
20
+ ACCOUNT_SIGNUP_FORM_CLASS = 'resonant_utils.allauth.FullNameSignupForm'
21
+ """
22
+
23
+ first_name = forms.CharField(
24
+ max_length=150,
25
+ label=_("First name"),
26
+ widget=forms.TextInput(
27
+ attrs={"placeholder": _("First name"), "autocomplete": "given-name"}
28
+ ),
29
+ )
30
+ last_name = forms.CharField(
31
+ max_length=150,
32
+ label=_("Last name"),
33
+ widget=forms.TextInput(
34
+ attrs={"placeholder": _("Last name"), "auto complete": "family-name"}
35
+ ),
36
+ )
37
+
38
+ field_order = [
39
+ # Any undefined fields in this list are just ignored
40
+ "first_name",
41
+ "last_name",
42
+ "email",
43
+ "email2",
44
+ "username",
45
+ "password1",
46
+ "password2",
47
+ ]
48
+
49
+ def signup(self, request: HttpRequest, user: AbstractUser) -> None:
50
+ # Allauth requires this method to be defined
51
+ pass
@@ -0,0 +1,7 @@
1
+ from __future__ import annotations
2
+
3
+ from django.apps import AppConfig
4
+
5
+
6
+ class ResonantUtilsConfig(AppConfig):
7
+ name = "resonant_utils"
@@ -0,0 +1,90 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, 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
+ if TYPE_CHECKING:
11
+ from collections.abc import Sequence
12
+ import json
13
+
14
+ _T_co = TypeVar("_T_co", bound=Model, covariant=True)
15
+
16
+
17
+ class JSONObjectField(models.JSONField):
18
+ """
19
+ A field for storing JSON Objects.
20
+
21
+ Other JSON types are not allowed at the top level.
22
+ """
23
+
24
+ @staticmethod
25
+ def _validate_is_object(val: Any) -> None:
26
+ """Validate that the value is a JSON Object (dict) at the top level."""
27
+ if not isinstance(val, dict):
28
+ raise ValidationError(_("Must be a JSON Object."))
29
+
30
+ empty_values: list[Any] = [{}]
31
+
32
+ # At this point in the class definition lifecycle,
33
+ # staticmethods aren't resolvable directly, so use "__func__"
34
+ # https://stackoverflow.com/questions/41921255/staticmethod-object-is-not-callable
35
+ # Additionally, MyPy has a bug here: https://github.com/python/mypy/issues/3482
36
+ default_validators = [_validate_is_object.__func__] # type: ignore[attr-defined]
37
+
38
+ def __init__(
39
+ self,
40
+ verbose_name: str | None = None,
41
+ name: str | None = None,
42
+ encoder: type[json.JSONEncoder] | None = None,
43
+ decoder: type[json.JSONDecoder] | None = None,
44
+ **kwargs: Any,
45
+ ) -> None:
46
+ kwargs["default"] = dict
47
+ kwargs["blank"] = True
48
+ super().__init__(
49
+ verbose_name=verbose_name, name=name, encoder=encoder, decoder=decoder, **kwargs
50
+ )
51
+
52
+ def deconstruct(self) -> tuple[str, str, Sequence[Any], dict[str, Any]]:
53
+ name, path, args, kwargs = super().deconstruct()
54
+ del kwargs["default"]
55
+ del kwargs["blank"]
56
+ return name, path, args, kwargs
57
+
58
+
59
+ class SelectRelatedManager(Manager[_T_co]):
60
+ """
61
+ A Manager which always follows specified foreign-key relationships.
62
+
63
+ For Models which very frequently need to follow foreign-key relationships
64
+ (e.g. to generate their own __str__), it may be best to make this the
65
+ "_default_manager", so many automatically generated queries are more
66
+ efficient. To do so, define a custom "objects" as the first
67
+ Manager in the Model:
68
+ objects = SelectRelatedManager('foreign_thing')
69
+
70
+ Passing no arguments makes this follow all the Model's non-null
71
+ foreign-key relationships.
72
+ """
73
+
74
+ def __init__(self, *related_fields: str) -> None:
75
+ self.related_fields: list[str] = list(related_fields)
76
+ super().__init__()
77
+
78
+ def get_queryset(self) -> QuerySet[_T_co]:
79
+ return super().get_queryset().select_related(*self.related_fields)
80
+
81
+
82
+ class DeferredFieldsManager(Manager[_T_co]):
83
+ """A Manager which defers loading specified fields within fetched Models."""
84
+
85
+ def __init__(self, *deferred_fields: str) -> None:
86
+ self.deferred_fields = deferred_fields
87
+ super().__init__()
88
+
89
+ def get_queryset(self) -> QuerySet[_T_co]:
90
+ return super().get_queryset().defer(*self.deferred_fields)
@@ -0,0 +1,52 @@
1
+ from __future__ import annotations
2
+
3
+ from contextlib import contextmanager
4
+ from pathlib import Path, PurePath
5
+ import shutil
6
+ import tempfile
7
+ from typing import TYPE_CHECKING
8
+
9
+ from django.core.files import File
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Generator
13
+
14
+ from django.db.models.fields.files import FieldFile
15
+
16
+
17
+ @contextmanager
18
+ def field_file_to_local_path(field_file: FieldFile) -> Generator[Path]:
19
+ """
20
+ Provide a filesystem path to the content of a FieldFile.
21
+
22
+ Normally, a FieldFile is usable as a Python file-like object, as:
23
+ `with model.field.open() as file_stream:`
24
+
25
+ However, in some use cases, particularly when invoking third-party libraries,
26
+ an actual filesystem path to the content is required. This context manager
27
+ provides this as:
28
+ `with field_file_to_local_path(model.field) as file_path:`
29
+
30
+ When this context manager exists, the filesystem content and path will be
31
+ garbage collected.
32
+ """
33
+ with field_file.open("rb"):
34
+ file_obj: File[bytes] = field_file.file
35
+
36
+ if type(file_obj) is File:
37
+ # When file_obj is an actual File, (typically backed by FileSystemStorage),
38
+ # it is already at a stable path on disk.
39
+ if file_obj.name is None:
40
+ raise TypeError('The File object "field_file.file" does not have a "name".')
41
+ yield Path(file_obj.name)
42
+ else:
43
+ # When file_obj is actually a subclass of File, it only provides a Python
44
+ # file-like object API. So, it must be copied to a stable path.
45
+ if field_file.name is None:
46
+ raise TypeError('The FieldFile object "field_file" does not have a "name".')
47
+ field_file_basename = PurePath(field_file.name).name
48
+ with tempfile.NamedTemporaryFile("wb", suffix=field_file_basename) as dest_stream:
49
+ shutil.copyfileobj(file_obj, dest_stream)
50
+ dest_stream.flush()
51
+
52
+ yield Path(dest_stream.name)
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+
6
+ from django.core.management import ManagementUtility
7
+ from django.core.management.color import color_style
8
+
9
+
10
+ def execute_from_command_line(argv: list[str] | None = None) -> None:
11
+ """Behave like `django.core.management.execute_from_command_line`, but print settings errors."""
12
+ utility = ManagementUtility(argv)
13
+ try:
14
+ utility.execute()
15
+ finally:
16
+ if utility.settings_exception is not None and "DJANGO_AUTO_COMPLETE" not in os.environ:
17
+ # A settings exception may exist after least 4 different code paths:
18
+ # * Clean return from successfully printing help, which will have already printed the
19
+ # settings error, but we'll accept a second print here, for a simpler implementation.
20
+ # * Clean return from running any other command
21
+ # * `sys.exit(1)` if a command cannot be found (possibly because it's from an app,
22
+ # which aren't loaded if settings fail)
23
+ # * `sys.exit(0)`, if autocomplete was invoked; we won't print here, to avoid spam (but
24
+ # we should still detect autocomplete natively, not hardcoding around `sys.exit(0)`)
25
+ style = color_style()
26
+ sys.stderr.write(
27
+ style.NOTICE(
28
+ "Note that settings are not properly configured "
29
+ f"(error: {utility.settings_exception}).\n"
30
+ )
31
+ )
@@ -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,55 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ from rest_framework.pagination import LimitOffsetPagination
6
+
7
+ if TYPE_CHECKING:
8
+ from rest_framework.request import Request
9
+ from rest_framework.response import Response
10
+
11
+
12
+ class BoundedLimitOffsetPagination(LimitOffsetPagination):
13
+ """
14
+ Pagination class that forces pagination with an upper bound.
15
+
16
+ DRF's built-in paginators such as LimitOffsetPagination will cause
17
+ your endpoints to return different structure based on whether or not
18
+ paging parameters were passed in the request. In most cases it's desirable
19
+ to force pagination on endpoints that could return large result sets.
20
+ Using this class has three benefits:
21
+
22
+ 1. It will always return responses in their paged structure, i.e. a
23
+ JSON Object with "count", and a "results" Array. This is achieved by
24
+ providing a default limit that is used if none is passed.
25
+ 2. It enforces a reasonable upper bound on page sizes. Without this, users could
26
+ circumvent the intent of pagination by simply providing a high enough limit.
27
+ 3. It adds the Link header to the response, making it easier for clients to
28
+ navigate through pages of results.
29
+
30
+ The default limit will be the value of DRF's normal PAGE_SIZE setting, or
31
+ the max limit if that is not set or falsy. The upper bound on the limit is 1000.
32
+ """
33
+
34
+ max_limit = 1000
35
+
36
+ def get_limit(self, request: Request) -> int:
37
+ return super().get_limit(request) or self.max_limit
38
+
39
+ def get_paginated_response(self, data: Any) -> Response:
40
+ response = super().get_paginated_response(data)
41
+
42
+ # Add links, per https://tools.ietf.org/html/rfc8288
43
+ links = [
44
+ # (relation_type, target)
45
+ ("prev", self.get_previous_link()),
46
+ ("next", self.get_next_link()),
47
+ ]
48
+ # Always set a Link header, even if it's empty
49
+ response["Link"] = ", ".join(
50
+ f'<{target}>; rel="{relation_type}"'
51
+ for relation_type, target in links
52
+ if target is not None
53
+ )
54
+
55
+ return response
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from datetime import timedelta
7
+
8
+ from django.core.files.storage import Storage
9
+
10
+ try:
11
+ from storages.backends.s3 import S3Storage
12
+ except ImportError:
13
+ # This should only be used for type interrogation, never instantiation
14
+ S3Storage = type("FakeS3Storage", (), {}) # type: ignore[assignment,misc]
15
+ try:
16
+ from minio_storage.storage import MinioStorage
17
+ except ImportError:
18
+ # This should only be used for type interrogation, never instantiation
19
+ MinioStorage = type("FakeMinioStorage", (), {}) # type: ignore[assignment,misc]
20
+
21
+
22
+ def expiring_url(storage: Storage, name: str, expiration: timedelta) -> str:
23
+ """
24
+ Return an expiring URL to a file name on a `Storage`.
25
+
26
+ `S3Storage` and `MinioStorage` are specifically supported.
27
+ """
28
+ # Each storage backend uses a slightly different API for URL expiration
29
+ if isinstance(storage, S3Storage):
30
+ return storage.url(name, expire=int(expiration.total_seconds()))
31
+ if isinstance(storage, MinioStorage):
32
+ return storage.url(name, max_age=expiration)
33
+ # Unsupported Storage type
34
+ return storage.url(name)
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import TYPE_CHECKING, Any, TypeVar
5
+ import warnings
6
+
7
+ from django import template
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Mapping
11
+
12
+ register = template.Library()
13
+
14
+
15
+ _KT = TypeVar("_KT")
16
+ _VT_co = TypeVar("_VT_co", covariant=True)
17
+
18
+
19
+ @register.filter
20
+ def get_item(value: Mapping[_KT, _VT_co], arg: _KT) -> _VT_co | None:
21
+ """
22
+ Retrieve `value[arg]` from a mapping `value`, where `arg` can be a variable.
23
+
24
+ This will return `None` if `arg` is not found. It may be useful to chain the `default_if_none`
25
+ filter after this one.
26
+
27
+ Sample usage::
28
+ {% load resonant_utils %}
29
+ {% for key in some_keys %}
30
+ {{ my_dict|getitem:key }}
31
+ {% endfor %}
32
+ """
33
+ return value.get(arg, None)
34
+
35
+
36
+ @register.filter
37
+ def getitem(value: Mapping[_KT, _VT_co], arg: _KT) -> _VT_co | None:
38
+ warnings.warn(
39
+ 'deprecated: use "get_item" instead of "getitem".', DeprecationWarning, stacklevel=2
40
+ )
41
+ return get_item(value, arg)
42
+
43
+
44
+ @register.filter
45
+ def pretty_json(value: Any, indent: int | None = None) -> str:
46
+ """
47
+ Convert `value` to a JSON-formatted string.
48
+
49
+ Optionally, `indent` can be specified as an positive integer number of spaces to pretty-print
50
+ indentation with; `None` (the default) will disable pretty-printing.
51
+
52
+ The output should typically be embedded within HTML an `<pre>` element.
53
+ If `indent` is specified, the output will likely contain newlines, which `<pre>` will render.
54
+
55
+ Sample usage::
56
+ {% load resonant_utils %}
57
+ <pre>{{ my_object|pretty_json:4 }}</pre>
58
+ """
59
+ return json.dumps(value, indent=indent)