feincms3-api 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- feincms3_api/__init__.py +1 -0
- feincms3_api/adapters.py +303 -0
- feincms3_api/admin.py +93 -0
- feincms3_api/api.py +66 -0
- feincms3_api/apps.py +70 -0
- feincms3_api/auth.py +29 -0
- feincms3_api/cabinet.py +78 -0
- feincms3_api/codecs.py +495 -0
- feincms3_api/conf.py +31 -0
- feincms3_api/content.py +312 -0
- feincms3_api/errors.py +53 -0
- feincms3_api/forms.py +36 -0
- feincms3_api/formsets.py +135 -0
- feincms3_api/http.py +195 -0
- feincms3_api/incubator/__init__.py +6 -0
- feincms3_api/incubator/autotranslate/__init__.py +0 -0
- feincms3_api/incubator/autotranslate/apps.py +47 -0
- feincms3_api/incubator/autotranslate/backends/__init__.py +78 -0
- feincms3_api/incubator/autotranslate/backends/anthropic.py +98 -0
- feincms3_api/incubator/autotranslate/conf.py +59 -0
- feincms3_api/incubator/autotranslate/datasets.py +428 -0
- feincms3_api/incubator/autotranslate/fields.py +213 -0
- feincms3_api/incubator/autotranslate/links.py +122 -0
- feincms3_api/incubator/autotranslate/loader.py +1250 -0
- feincms3_api/incubator/autotranslate/management/__init__.py +0 -0
- feincms3_api/incubator/autotranslate/management/commands/__init__.py +0 -0
- feincms3_api/incubator/autotranslate/management/commands/f3autotranslate.py +162 -0
- feincms3_api/incubator/autotranslate/management/commands/f3autotranslateload.py +92 -0
- feincms3_api/incubator/autotranslate/review.py +104 -0
- feincms3_api/incubator/autotranslate/strings.py +313 -0
- feincms3_api/incubator/autotranslate/translate.py +260 -0
- feincms3_api/kinds.py +86 -0
- feincms3_api/management/__init__.py +0 -0
- feincms3_api/management/commands/__init__.py +0 -0
- feincms3_api/management/commands/f3api_cleanup.py +18 -0
- feincms3_api/management/commands/f3api_schema.py +32 -0
- feincms3_api/management/commands/f3api_token.py +39 -0
- feincms3_api/migrations/0001_initial.py +91 -0
- feincms3_api/migrations/0002_upload.py +61 -0
- feincms3_api/migrations/__init__.py +0 -0
- feincms3_api/models.py +189 -0
- feincms3_api/paths.py +43 -0
- feincms3_api/reading.py +120 -0
- feincms3_api/references.py +123 -0
- feincms3_api/resources.py +580 -0
- feincms3_api/schema.py +80 -0
- feincms3_api/snapshot.py +110 -0
- feincms3_api/templates/admin/feincms3_api/apitoken/created.html +19 -0
- feincms3_api/writing.py +255 -0
- feincms3_api-0.0.1.dist-info/METADATA +69 -0
- feincms3_api-0.0.1.dist-info/RECORD +53 -0
- feincms3_api-0.0.1.dist-info/WHEEL +4 -0
- feincms3_api-0.0.1.dist-info/licenses/LICENSE +29 -0
feincms3_api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
feincms3_api/adapters.py
ADDED
|
@@ -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)
|
feincms3_api/admin.py
ADDED
|
@@ -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
|
+
)
|
feincms3_api/api.py
ADDED
|
@@ -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
|
feincms3_api/apps.py
ADDED
|
@@ -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
|
feincms3_api/auth.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from django.utils.translation import gettext as _
|
|
2
|
+
from ninja.errors import HttpError
|
|
3
|
+
from ninja.security import HttpBearer, SessionAuthIsStaff
|
|
4
|
+
|
|
5
|
+
from feincms3_api.models import APIToken
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TokenAuth(HttpBearer):
|
|
12
|
+
"""``Authorization: Bearer f3api_…`` with an ``APIToken``"""
|
|
13
|
+
|
|
14
|
+
def authenticate(self, request, token):
|
|
15
|
+
if (api_token := APIToken.objects.for_secret(token)) is None:
|
|
16
|
+
return None
|
|
17
|
+
if (
|
|
18
|
+
api_token.access == APIToken.Access.READ
|
|
19
|
+
and request.method not in SAFE_METHODS
|
|
20
|
+
):
|
|
21
|
+
raise HttpError(403, _("This API token only allows reading."))
|
|
22
|
+
request.user = api_token.user
|
|
23
|
+
request.api_token = api_token
|
|
24
|
+
return api_token.user
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def default_auth():
|
|
28
|
+
"""Tokens first: session auth fails without a CSRF token"""
|
|
29
|
+
return [TokenAuth(), SessionAuthIsStaff()]
|
feincms3_api/cabinet.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""
|
|
2
|
+
django-cabinet: files and folders
|
|
3
|
+
|
|
4
|
+
Files go through the file model's registered admin like any other resource;
|
|
5
|
+
their file fields take uploads (``{"upload": id}``). Folders have no admin
|
|
6
|
+
of their own in cabinet (the file admin edits them), so they get one here,
|
|
7
|
+
with cabinet's form and the folder model's permissions, as in cabinet.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from cabinet.base_admin import FolderForm
|
|
11
|
+
from cabinet.models import Folder, get_file_model
|
|
12
|
+
from django.contrib import admin
|
|
13
|
+
from django.urls import NoReverseMatch, reverse
|
|
14
|
+
from django.utils.functional import cached_property
|
|
15
|
+
|
|
16
|
+
from feincms3_api.errors import ConflictError
|
|
17
|
+
from feincms3_api.resources import ObjectResource
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FileResource(ObjectResource):
|
|
21
|
+
filter_fields = ("folder",)
|
|
22
|
+
|
|
23
|
+
def __init__(self, **kwargs):
|
|
24
|
+
kwargs.setdefault("name", "files")
|
|
25
|
+
super().__init__(get_file_model(), **kwargs)
|
|
26
|
+
|
|
27
|
+
def url(self, request, obj):
|
|
28
|
+
try:
|
|
29
|
+
url = obj.file.url
|
|
30
|
+
except ValueError:
|
|
31
|
+
return None
|
|
32
|
+
return request.build_absolute_uri(url)
|
|
33
|
+
|
|
34
|
+
def describe(self, request, obj):
|
|
35
|
+
description = super().describe(request, obj) | {
|
|
36
|
+
"name": obj.file_name,
|
|
37
|
+
"size": obj.file_size,
|
|
38
|
+
}
|
|
39
|
+
if getattr(obj, "image_file", None):
|
|
40
|
+
description |= {
|
|
41
|
+
"width": obj.image_width,
|
|
42
|
+
"height": obj.image_height,
|
|
43
|
+
"alt_text": obj.image_alt_text,
|
|
44
|
+
}
|
|
45
|
+
return description
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class FolderAdmin(admin.ModelAdmin):
|
|
49
|
+
form = FolderForm
|
|
50
|
+
fields = ["parent", "name"]
|
|
51
|
+
search_fields = ["name"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class FolderResource(ObjectResource):
|
|
55
|
+
filter_fields = ("parent",)
|
|
56
|
+
|
|
57
|
+
def __init__(self, **kwargs):
|
|
58
|
+
kwargs.setdefault("name", "folders")
|
|
59
|
+
super().__init__(Folder, **kwargs)
|
|
60
|
+
|
|
61
|
+
@cached_property
|
|
62
|
+
def model_admin(self):
|
|
63
|
+
return FolderAdmin(Folder, self.admin_site)
|
|
64
|
+
|
|
65
|
+
def admin_url(self, obj):
|
|
66
|
+
try:
|
|
67
|
+
return reverse(
|
|
68
|
+
f"{self.admin_site.name}:cabinet_folder_change", args=[obj.pk]
|
|
69
|
+
)
|
|
70
|
+
except NoReverseMatch:
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
def check_delete(self, request, obj):
|
|
74
|
+
if (
|
|
75
|
+
obj.children.exists()
|
|
76
|
+
or get_file_model()._default_manager.filter(folder=obj).exists()
|
|
77
|
+
):
|
|
78
|
+
raise ConflictError("The folder isn't empty.")
|