feincms3-api 0.0.1__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.
- feincms3_api-0.0.1/.gitignore +21 -0
- feincms3_api-0.0.1/LICENSE +29 -0
- feincms3_api-0.0.1/PKG-INFO +69 -0
- feincms3_api-0.0.1/README.md +31 -0
- feincms3_api-0.0.1/feincms3_api/__init__.py +1 -0
- feincms3_api-0.0.1/feincms3_api/adapters.py +303 -0
- feincms3_api-0.0.1/feincms3_api/admin.py +93 -0
- feincms3_api-0.0.1/feincms3_api/api.py +66 -0
- feincms3_api-0.0.1/feincms3_api/apps.py +70 -0
- feincms3_api-0.0.1/feincms3_api/auth.py +29 -0
- feincms3_api-0.0.1/feincms3_api/cabinet.py +78 -0
- feincms3_api-0.0.1/feincms3_api/codecs.py +495 -0
- feincms3_api-0.0.1/feincms3_api/conf.py +31 -0
- feincms3_api-0.0.1/feincms3_api/content.py +312 -0
- feincms3_api-0.0.1/feincms3_api/errors.py +53 -0
- feincms3_api-0.0.1/feincms3_api/forms.py +36 -0
- feincms3_api-0.0.1/feincms3_api/formsets.py +135 -0
- feincms3_api-0.0.1/feincms3_api/http.py +195 -0
- feincms3_api-0.0.1/feincms3_api/incubator/__init__.py +6 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/__init__.py +0 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/apps.py +47 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/backends/__init__.py +78 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/backends/anthropic.py +98 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/conf.py +59 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/datasets.py +428 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/fields.py +213 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/links.py +122 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/loader.py +1250 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/management/__init__.py +0 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/management/commands/__init__.py +0 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/management/commands/f3autotranslate.py +162 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/management/commands/f3autotranslateload.py +92 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/review.py +104 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/strings.py +313 -0
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/translate.py +260 -0
- feincms3_api-0.0.1/feincms3_api/kinds.py +86 -0
- feincms3_api-0.0.1/feincms3_api/management/__init__.py +0 -0
- feincms3_api-0.0.1/feincms3_api/management/commands/__init__.py +0 -0
- feincms3_api-0.0.1/feincms3_api/management/commands/f3api_cleanup.py +18 -0
- feincms3_api-0.0.1/feincms3_api/management/commands/f3api_schema.py +32 -0
- feincms3_api-0.0.1/feincms3_api/management/commands/f3api_token.py +39 -0
- feincms3_api-0.0.1/feincms3_api/migrations/0001_initial.py +91 -0
- feincms3_api-0.0.1/feincms3_api/migrations/0002_upload.py +61 -0
- feincms3_api-0.0.1/feincms3_api/migrations/__init__.py +0 -0
- feincms3_api-0.0.1/feincms3_api/models.py +189 -0
- feincms3_api-0.0.1/feincms3_api/paths.py +43 -0
- feincms3_api-0.0.1/feincms3_api/reading.py +120 -0
- feincms3_api-0.0.1/feincms3_api/references.py +123 -0
- feincms3_api-0.0.1/feincms3_api/resources.py +580 -0
- feincms3_api-0.0.1/feincms3_api/schema.py +80 -0
- feincms3_api-0.0.1/feincms3_api/snapshot.py +110 -0
- feincms3_api-0.0.1/feincms3_api/templates/admin/feincms3_api/apitoken/created.html +19 -0
- feincms3_api-0.0.1/feincms3_api/writing.py +255 -0
- feincms3_api-0.0.1/pyproject.toml +122 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, Feinheit AG
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without
|
|
7
|
+
modification, are permitted provided that the following conditions are met:
|
|
8
|
+
|
|
9
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
10
|
+
list of conditions and the following disclaimer.
|
|
11
|
+
|
|
12
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
13
|
+
this list of conditions and the following disclaimer in the documentation
|
|
14
|
+
and/or other materials provided with the distribution.
|
|
15
|
+
|
|
16
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
17
|
+
contributors may be used to endorse or promote products derived from
|
|
18
|
+
this software without specific prior written permission.
|
|
19
|
+
|
|
20
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
21
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
22
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
23
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
24
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
25
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
26
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
27
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
28
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
29
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: feincms3-api
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: A content API for feincms3 sites
|
|
5
|
+
Project-URL: Homepage, https://github.com/feincms/feincms3-api/
|
|
6
|
+
Author-email: Feinheit AG <dev@feinheit.ch>, Matthias Kestenholz <mk@feinheit.ch>, Moritz Wettstein <mw@feinheit.ch>
|
|
7
|
+
License-Expression: BSD-3-Clause
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Environment :: Web Environment
|
|
10
|
+
Classifier: Framework :: Django
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: django-content-editor>=10
|
|
22
|
+
Requires-Dist: django-ninja>=1.4
|
|
23
|
+
Requires-Dist: django>=5.2
|
|
24
|
+
Requires-Dist: feincms3-data>=0.11
|
|
25
|
+
Requires-Dist: feincms3>=7.1
|
|
26
|
+
Provides-Extra: anthropic
|
|
27
|
+
Requires-Dist: anthropic>=0.70; extra == 'anthropic'
|
|
28
|
+
Provides-Extra: tests
|
|
29
|
+
Requires-Dist: coverage; extra == 'tests'
|
|
30
|
+
Requires-Dist: django-cabinet; extra == 'tests'
|
|
31
|
+
Requires-Dist: django-json-schema-editor; extra == 'tests'
|
|
32
|
+
Requires-Dist: django-prose-editor; extra == 'tests'
|
|
33
|
+
Requires-Dist: django-translated-fields; extra == 'tests'
|
|
34
|
+
Requires-Dist: feincms3-forms; extra == 'tests'
|
|
35
|
+
Requires-Dist: feincms3-language-sites; extra == 'tests'
|
|
36
|
+
Requires-Dist: feincms3-sites>=0.23; extra == 'tests'
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
# feincms3-api
|
|
40
|
+
|
|
41
|
+
A [django-ninja](https://django-ninja.dev/) API for reading and writing the
|
|
42
|
+
content of [feincms3](https://feincms3.readthedocs.io/) sites: pages and
|
|
43
|
+
other objects with
|
|
44
|
+
[django-content-editor](https://django-content-editor.readthedocs.io/)
|
|
45
|
+
regions and plugins,
|
|
46
|
+
[django-json-schema-editor](https://github.com/matthiask/django-json-schema-editor)
|
|
47
|
+
data and [django-cabinet](https://github.com/matthiask/django-cabinet) files.
|
|
48
|
+
For scripts, importers and agents, next to the Django admin, not instead of
|
|
49
|
+
it.
|
|
50
|
+
|
|
51
|
+
**Status:** early development. Reading and writing objects and their
|
|
52
|
+
content work, with uploads, pages and django-cabinet. The plan is
|
|
53
|
+
in [specs/api.md](specs/api.md).
|
|
54
|
+
|
|
55
|
+
## Incubator
|
|
56
|
+
|
|
57
|
+
`feincms3_api.incubator` holds code which may become part of the package or
|
|
58
|
+
may go away: tested, but not documented as part of the package, and without
|
|
59
|
+
any promise of stability. At the moment that's
|
|
60
|
+
`feincms3_api.incubator.autotranslate`, which machine-translates feincms3
|
|
61
|
+
content and loads it as inactive copies, see
|
|
62
|
+
[docs/autotranslate.md](docs/autotranslate.md).
|
|
63
|
+
|
|
64
|
+
## Credits
|
|
65
|
+
|
|
66
|
+
feincms3-api grows out of feincms3-autotranslate, started by Moritz Wettstein
|
|
67
|
+
and Matthias Kestenholz at [Feinheit](https://www.feinheit.ch/) in October
|
|
68
|
+
2026. Its content introspection (which fields hold text, HTML or links, JSON
|
|
69
|
+
schemas, plugin discovery) is the base of this package.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# feincms3-api
|
|
2
|
+
|
|
3
|
+
A [django-ninja](https://django-ninja.dev/) API for reading and writing the
|
|
4
|
+
content of [feincms3](https://feincms3.readthedocs.io/) sites: pages and
|
|
5
|
+
other objects with
|
|
6
|
+
[django-content-editor](https://django-content-editor.readthedocs.io/)
|
|
7
|
+
regions and plugins,
|
|
8
|
+
[django-json-schema-editor](https://github.com/matthiask/django-json-schema-editor)
|
|
9
|
+
data and [django-cabinet](https://github.com/matthiask/django-cabinet) files.
|
|
10
|
+
For scripts, importers and agents, next to the Django admin, not instead of
|
|
11
|
+
it.
|
|
12
|
+
|
|
13
|
+
**Status:** early development. Reading and writing objects and their
|
|
14
|
+
content work, with uploads, pages and django-cabinet. The plan is
|
|
15
|
+
in [specs/api.md](specs/api.md).
|
|
16
|
+
|
|
17
|
+
## Incubator
|
|
18
|
+
|
|
19
|
+
`feincms3_api.incubator` holds code which may become part of the package or
|
|
20
|
+
may go away: tested, but not documented as part of the package, and without
|
|
21
|
+
any promise of stability. At the moment that's
|
|
22
|
+
`feincms3_api.incubator.autotranslate`, which machine-translates feincms3
|
|
23
|
+
content and loads it as inactive copies, see
|
|
24
|
+
[docs/autotranslate.md](docs/autotranslate.md).
|
|
25
|
+
|
|
26
|
+
## Credits
|
|
27
|
+
|
|
28
|
+
feincms3-api grows out of feincms3-autotranslate, started by Moritz Wettstein
|
|
29
|
+
and Matthias Kestenholz at [Feinheit](https://www.feinheit.ch/) in October
|
|
30
|
+
2026. Its content introspection (which fields hold text, HTML or links, JSON
|
|
31
|
+
schemas, plugin discovery) is the base of this package.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Adapters decide what an object's or a plugin's ``fields`` are
|
|
3
|
+
|
|
4
|
+
The default adapter is the admin's form: its fields, through the codecs.
|
|
5
|
+
That covers every plugin made of ordinary fields without any code. Projects
|
|
6
|
+
register their own adapter for a type only to change the shape.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
import dataclasses
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
from django import forms
|
|
14
|
+
from django.core.exceptions import FieldDoesNotExist, ValidationError
|
|
15
|
+
from django.db import models, transaction
|
|
16
|
+
|
|
17
|
+
from feincms3_api.codecs import Field, UploadRef, codecs as default_codecs
|
|
18
|
+
from feincms3_api.conf import excluded_paths
|
|
19
|
+
from feincms3_api.errors import WireError
|
|
20
|
+
from feincms3_api.paths import iter_path, tokens
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclasses.dataclass
|
|
24
|
+
class Context:
|
|
25
|
+
"""Everything an adapter needs to know about one type in one request"""
|
|
26
|
+
|
|
27
|
+
type: str
|
|
28
|
+
model: type[models.Model]
|
|
29
|
+
form_class: type[forms.BaseForm]
|
|
30
|
+
read_only: tuple = ()
|
|
31
|
+
exclude: frozenset = frozenset()
|
|
32
|
+
codecs: object = default_codecs
|
|
33
|
+
request: object = None
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def excluded_paths(self):
|
|
37
|
+
return excluded_paths(self.type)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RawWidget(forms.Widget):
|
|
41
|
+
"""
|
|
42
|
+
Hands a value to the form field's ``clean()`` as it is
|
|
43
|
+
|
|
44
|
+
The admin's widgets read HTML form data (a date and a time as
|
|
45
|
+
``name_0`` and ``name_1``, a checkbox as present or not). The API's
|
|
46
|
+
values are already what the fields clean, so the forms get this widget.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def value_from_datadict(self, data, files, name):
|
|
50
|
+
return data.get(name)
|
|
51
|
+
|
|
52
|
+
def value_omitted_from_data(self, data, files, name):
|
|
53
|
+
return name not in data
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def current_data(form):
|
|
57
|
+
"""An unbound form's initial values, as data its fields can clean"""
|
|
58
|
+
data = {}
|
|
59
|
+
for name, field in form.fields.items():
|
|
60
|
+
value = form.get_initial_for_field(field, name)
|
|
61
|
+
if isinstance(field, forms.FileField):
|
|
62
|
+
value = None # Keeps the file
|
|
63
|
+
elif isinstance(field, forms.MultiValueField):
|
|
64
|
+
value = field.widget.decompress(value)
|
|
65
|
+
elif isinstance(value, (list, tuple)):
|
|
66
|
+
value = [getattr(item, "pk", item) for item in value]
|
|
67
|
+
elif isinstance(value, models.Model):
|
|
68
|
+
value = value.pk
|
|
69
|
+
elif isinstance(value, dict):
|
|
70
|
+
value = copy.deepcopy(value) # Not the instance's own JSON
|
|
71
|
+
data[name] = value
|
|
72
|
+
return data
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def prepare_form(form, context, *, keep=()):
|
|
76
|
+
"""
|
|
77
|
+
Make a bound form take the API's data: fields the API sets itself (e.g.
|
|
78
|
+
a plugin's parent) aren't the form's business unless they're in
|
|
79
|
+
``keep``, and the values are cleaned as they are (``RawWidget``)
|
|
80
|
+
"""
|
|
81
|
+
for name in context.exclude:
|
|
82
|
+
if name not in keep:
|
|
83
|
+
form.fields.pop(name, None)
|
|
84
|
+
for form_field in form.fields.values():
|
|
85
|
+
form_field.widget = RawWidget()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def form_errors(form, path):
|
|
89
|
+
"""A bound form's errors as ``[{"path", "message"}]``"""
|
|
90
|
+
return [
|
|
91
|
+
{
|
|
92
|
+
"path": path if name == forms.forms.NON_FIELD_ERRORS else f"{path}.{name}",
|
|
93
|
+
"message": str(message),
|
|
94
|
+
}
|
|
95
|
+
for name, messages in form.errors.items()
|
|
96
|
+
for message in messages
|
|
97
|
+
]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _set_concrete(data, concrete, value):
|
|
101
|
+
"""Set ``value`` at a concrete path (``data.figures[0].unit``) if its
|
|
102
|
+
parents exist"""
|
|
103
|
+
keys = [
|
|
104
|
+
int(index) if index else name
|
|
105
|
+
for index, name in re.findall(r"\[(\d+)\]|([^.\[\]]+)", concrete)
|
|
106
|
+
]
|
|
107
|
+
node = data
|
|
108
|
+
for key in keys[:-1]:
|
|
109
|
+
try:
|
|
110
|
+
node = node[key]
|
|
111
|
+
except (KeyError, IndexError, TypeError):
|
|
112
|
+
return
|
|
113
|
+
last = keys[-1]
|
|
114
|
+
if (isinstance(node, dict) and isinstance(last, str)) or (
|
|
115
|
+
isinstance(node, list) and isinstance(last, int) and last < len(node)
|
|
116
|
+
):
|
|
117
|
+
node[last] = value
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def resolve_upload(request, ref):
|
|
121
|
+
"""
|
|
122
|
+
The uploaded file for a form, and its deletion once the write is
|
|
123
|
+
committed (a dry run or a failed write keeps it for another try)
|
|
124
|
+
"""
|
|
125
|
+
from feincms3_api.models import Upload # noqa: PLC0415
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
upload = Upload.objects.usable(request.user).get(pk=ref.id)
|
|
129
|
+
except (Upload.DoesNotExist, ValidationError, ValueError) as exc:
|
|
130
|
+
raise WireError("No such upload of yours, or it has expired.") from exc
|
|
131
|
+
transaction.on_commit(upload.discard)
|
|
132
|
+
return upload.as_file()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class FormAdapter:
|
|
136
|
+
def fields(self, context):
|
|
137
|
+
"""``(fields, excluded)``: the exposed fields, and why others aren't"""
|
|
138
|
+
exclude = context.exclude | {
|
|
139
|
+
path for path in context.excluded_paths if len(tokens(path)) == 1
|
|
140
|
+
}
|
|
141
|
+
fields, excluded = [], {}
|
|
142
|
+
for name, form_field in context.form_class.base_fields.items():
|
|
143
|
+
if name in exclude:
|
|
144
|
+
continue
|
|
145
|
+
if context.codecs.lookup(form_field) is None:
|
|
146
|
+
excluded[name] = f"no codec for {type(form_field).__name__}"
|
|
147
|
+
continue
|
|
148
|
+
read_only = name in context.read_only
|
|
149
|
+
fields.append(Field(name, form_field, context.model, read_only=read_only))
|
|
150
|
+
|
|
151
|
+
for name in context.read_only:
|
|
152
|
+
if name in exclude or name in context.form_class.base_fields:
|
|
153
|
+
continue
|
|
154
|
+
try:
|
|
155
|
+
model_field = context.model._meta.get_field(name)
|
|
156
|
+
except FieldDoesNotExist:
|
|
157
|
+
continue # A method or an admin callable, not data
|
|
158
|
+
form_field = getattr(model_field, "formfield", lambda: None)()
|
|
159
|
+
if form_field is None or context.codecs.lookup(form_field) is None:
|
|
160
|
+
continue
|
|
161
|
+
fields.append(Field(name, form_field, context.model, read_only=True))
|
|
162
|
+
return fields, excluded
|
|
163
|
+
|
|
164
|
+
def to_wire(self, context, obj):
|
|
165
|
+
fields, _excluded = self.fields(context)
|
|
166
|
+
form = context.form_class(instance=obj) if obj is not None else None
|
|
167
|
+
data = {}
|
|
168
|
+
for field in fields:
|
|
169
|
+
if field.read_only and field.model_field is not None:
|
|
170
|
+
value = field.model_field.value_from_object(obj)
|
|
171
|
+
else:
|
|
172
|
+
value = form.get_initial_for_field(field.form_field, field.name)
|
|
173
|
+
codec = context.codecs.lookup(field.form_field)
|
|
174
|
+
data[field.name] = codec.to_wire(value, field)
|
|
175
|
+
# The values may be the instance's own JSON data: remove from a copy.
|
|
176
|
+
data = copy.deepcopy(data)
|
|
177
|
+
_remove_paths(data, context.excluded_paths)
|
|
178
|
+
return data
|
|
179
|
+
|
|
180
|
+
def form_data(self, context, instance, wire, *, path, extra=None):
|
|
181
|
+
"""
|
|
182
|
+
``(form data, errors)``: the current values, with the wire fields
|
|
183
|
+
decoded over them, and ``extra`` (form data, e.g. a plugin's region)
|
|
184
|
+
|
|
185
|
+
A field which isn't sent keeps its value. Read-only fields may be
|
|
186
|
+
sent unchanged, so what was read can be written back. Values inside
|
|
187
|
+
JSON data which ``EXCLUDE_FIELDS`` hides are kept as they were, by
|
|
188
|
+
their position.
|
|
189
|
+
"""
|
|
190
|
+
errors = []
|
|
191
|
+
if not isinstance(wire, dict):
|
|
192
|
+
return None, [{"path": path, "message": "Expected an object."}]
|
|
193
|
+
fields, _excluded = self.fields(context)
|
|
194
|
+
by_name = {field.name: field for field in fields}
|
|
195
|
+
unbound = context.form_class(instance=instance)
|
|
196
|
+
data = current_data(unbound)
|
|
197
|
+
current = (
|
|
198
|
+
self.to_wire(context, instance)
|
|
199
|
+
if wire and instance is not None and instance.pk is not None
|
|
200
|
+
else {}
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
for name, value in wire.items():
|
|
204
|
+
field_path = f"{path}.{name}"
|
|
205
|
+
if (field := by_name.get(name)) is None:
|
|
206
|
+
errors.append({"path": field_path, "message": "Unknown field."})
|
|
207
|
+
elif field.read_only:
|
|
208
|
+
if instance is None or value != current.get(name):
|
|
209
|
+
errors.append({"path": field_path, "message": "Read-only."})
|
|
210
|
+
else:
|
|
211
|
+
try:
|
|
212
|
+
data[name] = self.decode(context, field, value, data.get(name))
|
|
213
|
+
except WireError as exc:
|
|
214
|
+
errors.append({"path": field_path, "message": str(exc)})
|
|
215
|
+
|
|
216
|
+
data.update(extra or {})
|
|
217
|
+
return data, errors
|
|
218
|
+
|
|
219
|
+
def bind(self, context, instance, wire, *, path, extra=None):
|
|
220
|
+
"""``(bound form, errors)``, with ``form_data()``"""
|
|
221
|
+
data, errors = self.form_data(context, instance, wire, path=path, extra=extra)
|
|
222
|
+
if data is None:
|
|
223
|
+
return None, errors
|
|
224
|
+
form = context.form_class(data=data, files={}, instance=instance)
|
|
225
|
+
prepare_form(form, context, keep=extra or ())
|
|
226
|
+
return form, errors
|
|
227
|
+
|
|
228
|
+
def decode(self, context, field, value, current):
|
|
229
|
+
"""
|
|
230
|
+
One wire value as form data; ``current`` is the field's current form
|
|
231
|
+
data, for the values inside JSON which ``EXCLUDE_FIELDS`` hides
|
|
232
|
+
"""
|
|
233
|
+
decoded = context.codecs.lookup(field.form_field).from_wire(value, field)
|
|
234
|
+
if isinstance(decoded, UploadRef):
|
|
235
|
+
return resolve_upload(context.request, decoded)
|
|
236
|
+
hidden = [
|
|
237
|
+
path
|
|
238
|
+
for path in context.excluded_paths
|
|
239
|
+
if len(tokens(path)) > 1 and tokens(path)[0] == field.name
|
|
240
|
+
]
|
|
241
|
+
if hidden and isinstance(decoded, (dict, list)):
|
|
242
|
+
old, new = {field.name: current}, {field.name: decoded}
|
|
243
|
+
for hidden_path in hidden:
|
|
244
|
+
for concrete, container, key in iter_path(old, hidden_path):
|
|
245
|
+
_set_concrete(new, concrete, container[key])
|
|
246
|
+
decoded = new[field.name]
|
|
247
|
+
return decoded
|
|
248
|
+
|
|
249
|
+
def json_schema(self, context):
|
|
250
|
+
fields, excluded = self.fields(context)
|
|
251
|
+
properties, required = {}, []
|
|
252
|
+
for field in fields:
|
|
253
|
+
schema = context.codecs.lookup(field.form_field).json_schema(field)
|
|
254
|
+
if field.read_only:
|
|
255
|
+
schema = {**schema, "readOnly": True}
|
|
256
|
+
elif field.form_field.required:
|
|
257
|
+
required.append(field.name)
|
|
258
|
+
if title := field.form_field.label:
|
|
259
|
+
schema.setdefault("title", str(title))
|
|
260
|
+
if help_text := field.form_field.help_text:
|
|
261
|
+
schema.setdefault("description", str(help_text))
|
|
262
|
+
properties[field.name] = schema
|
|
263
|
+
schema = {"type": "object", "properties": properties}
|
|
264
|
+
if required:
|
|
265
|
+
schema["required"] = required
|
|
266
|
+
for path in context.excluded_paths:
|
|
267
|
+
_remove_schema_path(schema, path)
|
|
268
|
+
if excluded:
|
|
269
|
+
schema["x-feincms3-excluded"] = excluded
|
|
270
|
+
return schema
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _remove_paths(data, paths):
|
|
274
|
+
for path in paths:
|
|
275
|
+
if len(tokens(path)) > 1:
|
|
276
|
+
for _concrete, container, key in reversed(list(iter_path(data, path))):
|
|
277
|
+
del container[key]
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _remove_schema_path(schema, path):
|
|
281
|
+
*parents, last = tokens(path)
|
|
282
|
+
node = schema
|
|
283
|
+
for token in parents:
|
|
284
|
+
if token is None:
|
|
285
|
+
node = node.get("items", {})
|
|
286
|
+
else:
|
|
287
|
+
node = node.get("properties", {}).get(token, {})
|
|
288
|
+
if last is not None:
|
|
289
|
+
node.get("properties", {}).pop(last, None)
|
|
290
|
+
if last in node.get("required", ()):
|
|
291
|
+
node["required"].remove(last)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
class AdapterRegistry:
|
|
295
|
+
def __init__(self, default=None):
|
|
296
|
+
self.default = default or FormAdapter()
|
|
297
|
+
self._adapters = {}
|
|
298
|
+
|
|
299
|
+
def register(self, type_label, adapter):
|
|
300
|
+
self._adapters[type_label] = adapter
|
|
301
|
+
|
|
302
|
+
def lookup(self, type_label):
|
|
303
|
+
return self._adapters.get(type_label, self.default)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from django.contrib import admin
|
|
2
|
+
from django.template.response import TemplateResponse
|
|
3
|
+
from django.utils.translation import gettext_lazy as _
|
|
4
|
+
|
|
5
|
+
from feincms3_api.models import APIToken
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@admin.register(APIToken)
|
|
9
|
+
class APITokenAdmin(admin.ModelAdmin):
|
|
10
|
+
"""
|
|
11
|
+
Every active staff user manages their own tokens, superusers everyone's
|
|
12
|
+
|
|
13
|
+
A token never acts with more permissions than its user, so creating one
|
|
14
|
+
needs no permission of its own. The secret is shown once, on a page of
|
|
15
|
+
its own after saving.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
list_display = [
|
|
19
|
+
"name",
|
|
20
|
+
"user",
|
|
21
|
+
"access",
|
|
22
|
+
"prefix",
|
|
23
|
+
"created_at",
|
|
24
|
+
"expires_at",
|
|
25
|
+
"last_used_at",
|
|
26
|
+
]
|
|
27
|
+
list_filter = ["access"]
|
|
28
|
+
search_fields = ["name", "prefix"]
|
|
29
|
+
readonly_fields = ["prefix", "created_at", "last_used_at"]
|
|
30
|
+
|
|
31
|
+
def get_queryset(self, request):
|
|
32
|
+
queryset = super().get_queryset(request).select_related("user")
|
|
33
|
+
if request.user.is_superuser:
|
|
34
|
+
return queryset
|
|
35
|
+
return queryset.filter(user=request.user)
|
|
36
|
+
|
|
37
|
+
def get_fields(self, request, obj=None):
|
|
38
|
+
fields = ["name", "access", "expires_at"]
|
|
39
|
+
if request.user.is_superuser or obj is not None:
|
|
40
|
+
fields.insert(0, "user")
|
|
41
|
+
if obj is not None:
|
|
42
|
+
fields += self.readonly_fields
|
|
43
|
+
return fields
|
|
44
|
+
|
|
45
|
+
def get_readonly_fields(self, request, obj=None):
|
|
46
|
+
if obj is not None:
|
|
47
|
+
return ["user", *self.readonly_fields]
|
|
48
|
+
return self.readonly_fields
|
|
49
|
+
|
|
50
|
+
def get_list_display(self, request):
|
|
51
|
+
if request.user.is_superuser:
|
|
52
|
+
return self.list_display
|
|
53
|
+
return [field for field in self.list_display if field != "user"]
|
|
54
|
+
|
|
55
|
+
def _is_own(self, request, obj):
|
|
56
|
+
return obj is None or request.user.is_superuser or obj.user == request.user
|
|
57
|
+
|
|
58
|
+
def has_module_permission(self, request):
|
|
59
|
+
return request.user.is_active and request.user.is_staff
|
|
60
|
+
|
|
61
|
+
def has_view_permission(self, request, obj=None):
|
|
62
|
+
return self.has_module_permission(request) and self._is_own(request, obj)
|
|
63
|
+
|
|
64
|
+
def has_add_permission(self, request):
|
|
65
|
+
return self.has_module_permission(request)
|
|
66
|
+
|
|
67
|
+
def has_change_permission(self, request, obj=None):
|
|
68
|
+
return self.has_view_permission(request, obj)
|
|
69
|
+
|
|
70
|
+
def has_delete_permission(self, request, obj=None):
|
|
71
|
+
return self.has_view_permission(request, obj)
|
|
72
|
+
|
|
73
|
+
def save_model(self, request, obj, form, change):
|
|
74
|
+
if not change:
|
|
75
|
+
if not request.user.is_superuser or not obj.user_id:
|
|
76
|
+
obj.user = request.user
|
|
77
|
+
obj._secret = obj.set_secret()
|
|
78
|
+
super().save_model(request, obj, form, change)
|
|
79
|
+
|
|
80
|
+
def response_add(self, request, obj, post_url_continue=None):
|
|
81
|
+
if (secret := getattr(obj, "_secret", None)) is None: # pragma: no cover
|
|
82
|
+
return super().response_add(request, obj, post_url_continue)
|
|
83
|
+
return TemplateResponse(
|
|
84
|
+
request,
|
|
85
|
+
"admin/feincms3_api/apitoken/created.html",
|
|
86
|
+
{
|
|
87
|
+
**self.admin_site.each_context(request),
|
|
88
|
+
"title": _("API token created"),
|
|
89
|
+
"opts": self.opts,
|
|
90
|
+
"token": obj,
|
|
91
|
+
"secret": secret,
|
|
92
|
+
},
|
|
93
|
+
)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The content API: registered resources, the operations on them, and the
|
|
3
|
+
django-ninja router exposing them
|
|
4
|
+
|
|
5
|
+
The operations are plain methods taking a request (for the admin's methods,
|
|
6
|
+
which need one) and returning wire data. The endpoints only wrap them, so
|
|
7
|
+
management commands and other code can use them without HTTP, also several
|
|
8
|
+
of them in one transaction.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from django.utils.functional import cached_property
|
|
12
|
+
from ninja import NinjaAPI
|
|
13
|
+
|
|
14
|
+
from feincms3_api.adapters import AdapterRegistry
|
|
15
|
+
from feincms3_api.auth import default_auth
|
|
16
|
+
from feincms3_api.codecs import codecs as default_codecs
|
|
17
|
+
from feincms3_api.errors import NotFoundError
|
|
18
|
+
from feincms3_api.reading import ReadingMixin
|
|
19
|
+
from feincms3_api.schema import SchemaMixin
|
|
20
|
+
from feincms3_api.writing import WritingMixin
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_instances = []
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ContentAPI(ReadingMixin, SchemaMixin, WritingMixin):
|
|
27
|
+
def __init__(self, *, auth=None, codecs=None, adapters=None):
|
|
28
|
+
self.auth = auth if auth is not None else default_auth()
|
|
29
|
+
self.codecs = codecs or default_codecs.copy()
|
|
30
|
+
self.adapters = adapters or AdapterRegistry()
|
|
31
|
+
self._resources = {}
|
|
32
|
+
_instances.append(self)
|
|
33
|
+
|
|
34
|
+
# Registration ###########################################################
|
|
35
|
+
|
|
36
|
+
def register(self, resource):
|
|
37
|
+
if "router" in self.__dict__:
|
|
38
|
+
raise RuntimeError("Register resources before using the router.")
|
|
39
|
+
if resource.name in self._resources or resource.name in {"schema", "uploads"}:
|
|
40
|
+
raise ValueError(f"The resource name {resource.name!r} is taken.")
|
|
41
|
+
self._resources[resource.name] = resource
|
|
42
|
+
return resource
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def resources(self):
|
|
46
|
+
return list(self._resources.values())
|
|
47
|
+
|
|
48
|
+
def resource(self, name):
|
|
49
|
+
try:
|
|
50
|
+
return self._resources[name]
|
|
51
|
+
except KeyError as exc:
|
|
52
|
+
raise NotFoundError(f"No resource {name!r}.") from exc
|
|
53
|
+
|
|
54
|
+
@cached_property
|
|
55
|
+
def router(self):
|
|
56
|
+
from feincms3_api.http import build_router # noqa: PLC0415
|
|
57
|
+
|
|
58
|
+
return build_router(self)
|
|
59
|
+
|
|
60
|
+
def as_api(self, **kwargs):
|
|
61
|
+
"""A ``NinjaAPI`` of its own, for projects without one"""
|
|
62
|
+
kwargs.setdefault("title", "Content API")
|
|
63
|
+
kwargs.setdefault("urls_namespace", "feincms3_api")
|
|
64
|
+
api = NinjaAPI(**kwargs)
|
|
65
|
+
api.add_router("/", self.router)
|
|
66
|
+
return api
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
|
|
3
|
+
from django.apps import AppConfig, apps
|
|
4
|
+
from django.core import checks
|
|
5
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Feincms3APIConfig(AppConfig):
|
|
9
|
+
name = "feincms3_api"
|
|
10
|
+
verbose_name = "feincms3-api"
|
|
11
|
+
default_auto_field = "django.db.models.AutoField"
|
|
12
|
+
|
|
13
|
+
def ready(self):
|
|
14
|
+
checks.register(check_resources)
|
|
15
|
+
checks.register(check_exclude_fields)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _content_apis():
|
|
19
|
+
# Content APIs are usually created where the URLs are, so load them.
|
|
20
|
+
from django.urls import get_resolver # noqa: PLC0415
|
|
21
|
+
|
|
22
|
+
from feincms3_api.api import _instances # noqa: PLC0415
|
|
23
|
+
|
|
24
|
+
# Django's own URL checks report an URLconf which doesn't load.
|
|
25
|
+
with contextlib.suppress(Exception):
|
|
26
|
+
get_resolver().url_patterns # noqa: B018
|
|
27
|
+
return list(_instances)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def check_resources(app_configs=None, **kwargs):
|
|
31
|
+
errors = []
|
|
32
|
+
for api in _content_apis():
|
|
33
|
+
for resource in api.resources:
|
|
34
|
+
try:
|
|
35
|
+
resource.model_admin # noqa: B018
|
|
36
|
+
except ImproperlyConfigured:
|
|
37
|
+
errors.append(
|
|
38
|
+
checks.Error(
|
|
39
|
+
f"{resource.type} is registered with a content API but"
|
|
40
|
+
f" not with the admin site {resource.admin_site.name!r}.",
|
|
41
|
+
hint="The API takes its forms and permissions from the admin.",
|
|
42
|
+
id="feincms3_api.E001",
|
|
43
|
+
)
|
|
44
|
+
)
|
|
45
|
+
return errors
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def check_exclude_fields(app_configs=None, **kwargs):
|
|
49
|
+
from feincms3_api.conf import config # noqa: PLC0415
|
|
50
|
+
from feincms3_api.paths import tokens # noqa: PLC0415
|
|
51
|
+
|
|
52
|
+
errors = []
|
|
53
|
+
for entry in config()["EXCLUDE_FIELDS"]:
|
|
54
|
+
app_label, _sep, rest = entry.strip().partition(".")
|
|
55
|
+
model_name, _sep, path = rest.partition(".")
|
|
56
|
+
try:
|
|
57
|
+
model = apps.get_model(app_label, model_name)
|
|
58
|
+
except (LookupError, ValueError):
|
|
59
|
+
model = None
|
|
60
|
+
names = {field.name for field in model._meta.get_fields()} if model else set()
|
|
61
|
+
first = tokens(path)[0] if path else None
|
|
62
|
+
if first is None or first not in names:
|
|
63
|
+
errors.append(
|
|
64
|
+
checks.Error(
|
|
65
|
+
f"FEINCMS3_API['EXCLUDE_FIELDS'] entry {entry!r} names no"
|
|
66
|
+
" model and field.",
|
|
67
|
+
id="feincms3_api.E002",
|
|
68
|
+
)
|
|
69
|
+
)
|
|
70
|
+
return errors
|