feincms3-api 0.0.1__tar.gz → 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 → feincms3_api-0.1}/.gitignore +1 -0
- feincms3_api-0.1/PKG-INFO +184 -0
- feincms3_api-0.1/README.md +147 -0
- feincms3_api-0.1/feincms3_api/__init__.py +1 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/api.py +14 -2
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/apps.py +17 -1
- feincms3_api-0.1/feincms3_api/batch.py +211 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/codecs.py +39 -1
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/conf.py +2 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/content.py +1 -1
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/http.py +93 -24
- feincms3_api-0.1/feincms3_api/openapi.py +457 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/reading.py +9 -2
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/resources.py +99 -29
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/schema.py +14 -4
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/writing.py +82 -21
- {feincms3_api-0.0.1 → feincms3_api-0.1}/pyproject.toml +3 -8
- feincms3_api-0.0.1/PKG-INFO +0 -69
- feincms3_api-0.0.1/README.md +0 -31
- feincms3_api-0.0.1/feincms3_api/__init__.py +0 -1
- feincms3_api-0.0.1/feincms3_api/incubator/__init__.py +0 -6
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/apps.py +0 -47
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/backends/__init__.py +0 -78
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/backends/anthropic.py +0 -98
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/conf.py +0 -59
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/datasets.py +0 -428
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/fields.py +0 -213
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/links.py +0 -122
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/loader.py +0 -1250
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/management/commands/f3autotranslate.py +0 -162
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/management/commands/f3autotranslateload.py +0 -92
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/review.py +0 -104
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/strings.py +0 -313
- feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/translate.py +0 -260
- 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/migrations/__init__.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/LICENSE +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/adapters.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/admin.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/auth.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/cabinet.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/errors.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/forms.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/formsets.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/kinds.py +0 -0
- {feincms3_api-0.0.1/feincms3_api/incubator/autotranslate → feincms3_api-0.1/feincms3_api/management}/__init__.py +0 -0
- {feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/management → feincms3_api-0.1/feincms3_api/management/commands}/__init__.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/management/commands/f3api_cleanup.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/management/commands/f3api_schema.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/management/commands/f3api_token.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/migrations/0001_initial.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/migrations/0002_upload.py +0 -0
- {feincms3_api-0.0.1/feincms3_api/incubator/autotranslate/management/commands → feincms3_api-0.1/feincms3_api/migrations}/__init__.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/models.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/paths.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/references.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/snapshot.py +0 -0
- {feincms3_api-0.0.1 → feincms3_api-0.1}/feincms3_api/templates/admin/feincms3_api/apitoken/created.html +0 -0
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: feincms3-api
|
|
3
|
+
Version: 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: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Environment :: Web Environment
|
|
11
|
+
Classifier: Framework :: Django
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: django-content-editor>=10
|
|
23
|
+
Requires-Dist: django-ninja>=1.4
|
|
24
|
+
Requires-Dist: django>=5.2
|
|
25
|
+
Requires-Dist: feincms3>=7.1
|
|
26
|
+
Provides-Extra: tests
|
|
27
|
+
Requires-Dist: coverage; extra == 'tests'
|
|
28
|
+
Requires-Dist: django-cabinet; extra == 'tests'
|
|
29
|
+
Requires-Dist: django-json-schema-editor; extra == 'tests'
|
|
30
|
+
Requires-Dist: django-prose-editor[sanitize]; extra == 'tests'
|
|
31
|
+
Requires-Dist: django-translated-fields; extra == 'tests'
|
|
32
|
+
Requires-Dist: feincms3-forms; extra == 'tests'
|
|
33
|
+
Requires-Dist: feincms3-language-sites; extra == 'tests'
|
|
34
|
+
Requires-Dist: feincms3-sites>=0.23; extra == 'tests'
|
|
35
|
+
Requires-Dist: openapi-spec-validator; extra == 'tests'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# feincms3-api
|
|
39
|
+
|
|
40
|
+
A [django-ninja](https://django-ninja.dev/) API for reading and writing the
|
|
41
|
+
content of [feincms3](https://feincms3.readthedocs.io/) sites: pages and
|
|
42
|
+
other objects with
|
|
43
|
+
[django-content-editor](https://django-content-editor.readthedocs.io/)
|
|
44
|
+
regions and plugins,
|
|
45
|
+
[django-json-schema-editor](https://github.com/matthiask/django-json-schema-editor)
|
|
46
|
+
data and [django-cabinet](https://github.com/matthiask/django-cabinet) files.
|
|
47
|
+
For scripts, importers and agents, next to the Django admin, not instead of
|
|
48
|
+
it.
|
|
49
|
+
|
|
50
|
+
**Status:** alpha. The wire format and the Python API may still change.
|
|
51
|
+
|
|
52
|
+
The admin is the source of truth: the API finds, validates, saves and
|
|
53
|
+
permits exactly what the admin does, through the admin's querysets, forms,
|
|
54
|
+
formsets, save hooks and permissions. A plugin with custom validation, or a
|
|
55
|
+
project hooking `save_formset()`, behaves the same through the API without
|
|
56
|
+
any code for the API.
|
|
57
|
+
|
|
58
|
+
- [How it's built](https://github.com/feincms/feincms3-api/blob/main/docs/architecture.md): the modules and where a project
|
|
59
|
+
plugs in.
|
|
60
|
+
- [The spec](https://github.com/feincms/feincms3-api/blob/main/specs/api.md): the design and the reasoning behind it.
|
|
61
|
+
- [Issues](https://github.com/feincms/feincms3-api/issues): what's planned.
|
|
62
|
+
- [feincms3-api-cli](https://github.com/feincms/feincms3-api/blob/main/cli/README.md): the API from the command line
|
|
63
|
+
(`f3api`), for people and agents with a shell.
|
|
64
|
+
- [Translating](https://github.com/feincms/feincms3-api/blob/main/docs/translating.md) content over the API.
|
|
65
|
+
|
|
66
|
+
## Setup
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
pip install feincms3-api
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
INSTALLED_APPS = [
|
|
74
|
+
...,
|
|
75
|
+
"feincms3_api",
|
|
76
|
+
]
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Register what the API exposes; nothing else is. Each model needs a
|
|
80
|
+
`ModelAdmin`, that's where the forms, permissions and plugins come from:
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
# app/content_api.py
|
|
84
|
+
from feincms3_api.api import ContentAPI
|
|
85
|
+
from feincms3_api.cabinet import FileResource, FolderResource
|
|
86
|
+
from feincms3_api.forms import ConfiguredFormResource
|
|
87
|
+
from feincms3_api.resources import ObjectResource, PageResource, TreeResource
|
|
88
|
+
|
|
89
|
+
from app.articles.models import Article
|
|
90
|
+
from app.forms.models import Form
|
|
91
|
+
from app.pages.models import Page
|
|
92
|
+
|
|
93
|
+
content_api = ContentAPI()
|
|
94
|
+
content_api.register(PageResource(Page))
|
|
95
|
+
content_api.register(ObjectResource(Article))
|
|
96
|
+
content_api.register(ConfiguredFormResource(Form)) # feincms3-forms
|
|
97
|
+
content_api.register(FileResource()) # django-cabinet
|
|
98
|
+
content_api.register(FolderResource())
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Mount it, either as an API of its own or as a router in an existing
|
|
102
|
+
`NinjaAPI`:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
# app/urls.py
|
|
106
|
+
from app.content_api import content_api
|
|
107
|
+
|
|
108
|
+
urlpatterns = [
|
|
109
|
+
...,
|
|
110
|
+
path("api/content/", content_api.as_api().urls),
|
|
111
|
+
]
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`./manage.py migrate` creates the tables for tokens and uploads. The
|
|
115
|
+
interactive docs are at `api/content/docs`.
|
|
116
|
+
|
|
117
|
+
### Settings
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
FEINCMS3_API = {
|
|
121
|
+
# Never exposed: fields, or values inside JSON data
|
|
122
|
+
"EXCLUDE_FIELDS": [
|
|
123
|
+
"forms.form.recipient_email",
|
|
124
|
+
"pages.jsonplugin_key_figures.data.internal_note",
|
|
125
|
+
],
|
|
126
|
+
"DEFAULT_PAGE_SIZE": 50,
|
|
127
|
+
"MAX_PAGE_SIZE": 200,
|
|
128
|
+
"TOKEN_LIFETIME": timedelta(hours=8),
|
|
129
|
+
"UPLOAD_LIFETIME": timedelta(days=1),
|
|
130
|
+
"UPLOAD_STORAGE": "default",
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### The schema snapshot
|
|
135
|
+
|
|
136
|
+
`./manage.py f3api_schema app.content_api.content_api` prints every type
|
|
137
|
+
with its fields and what kind of value each is, as a superuser sees them.
|
|
138
|
+
Commit it and compare it in a test, so a new plugin or field becomes
|
|
139
|
+
visible through the API only after someone looked at the diff.
|
|
140
|
+
|
|
141
|
+
## Using it
|
|
142
|
+
|
|
143
|
+
Only active staff users can use the API, with their admin permissions.
|
|
144
|
+
Scripts and agents use tokens: staff users create their own in the admin
|
|
145
|
+
(the secret is shown once), or `./manage.py f3api_token USERNAME --write`
|
|
146
|
+
prints one. Tokens are read-only unless created for writing, and expire
|
|
147
|
+
after `TOKEN_LIFETIME`. `./manage.py f3api_cleanup` removes expired tokens
|
|
148
|
+
and uploads; run it daily.
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
API=https://example.com/api/content
|
|
152
|
+
AUTH="Authorization: Bearer f3api_…"
|
|
153
|
+
|
|
154
|
+
curl -H "$AUTH" $API/schema/ # what's there
|
|
155
|
+
curl -H "$AUTH" "$API/pages/find/?path=/de/angebot/"
|
|
156
|
+
curl -H "$AUTH" "$API/pages/17/?expand=references" # one page with its content
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Writes need the ETag of what was read (`If-Match`), and fail as a whole with
|
|
160
|
+
every problem and its path. `?dry_run=true` runs a write in a transaction
|
|
161
|
+
which is rolled back and returns what it would have done:
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
curl -X PUT -H "$AUTH" -H 'If-Match: "9f2c…"' -H "Content-Type: application/json" \
|
|
165
|
+
"$API/pages/17/content/?dry_run=true" \
|
|
166
|
+
-d '{"content": {"main": [
|
|
167
|
+
{"type": "pages.richtext", "fields": {"text": "<h2>Hello</h2>"}}
|
|
168
|
+
]}}'
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
**A dry run runs everything but the commit**, signal handlers included:
|
|
172
|
+
anything they do outside the database (sending mail, calling other APIs,
|
|
173
|
+
writing files) happens in a dry run too.
|
|
174
|
+
|
|
175
|
+
Files are uploaded first (`POST /uploads/`, multipart) and then named in a
|
|
176
|
+
write as `{"upload": "<id>"}`. Changes appear in the admin's history,
|
|
177
|
+
marked "(Through the API.)".
|
|
178
|
+
|
|
179
|
+
## Credits
|
|
180
|
+
|
|
181
|
+
feincms3-api grows out of feincms3-autotranslate, started by Moritz Wettstein
|
|
182
|
+
and Matthias Kestenholz at [Feinheit](https://www.feinheit.ch/) in October
|
|
183
|
+
2026. Its content introspection (which fields hold text, HTML or links, JSON
|
|
184
|
+
schemas, plugin discovery) is the base of this package.
|
|
@@ -0,0 +1,147 @@
|
|
|
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:** alpha. The wire format and the Python API may still change.
|
|
14
|
+
|
|
15
|
+
The admin is the source of truth: the API finds, validates, saves and
|
|
16
|
+
permits exactly what the admin does, through the admin's querysets, forms,
|
|
17
|
+
formsets, save hooks and permissions. A plugin with custom validation, or a
|
|
18
|
+
project hooking `save_formset()`, behaves the same through the API without
|
|
19
|
+
any code for the API.
|
|
20
|
+
|
|
21
|
+
- [How it's built](https://github.com/feincms/feincms3-api/blob/main/docs/architecture.md): the modules and where a project
|
|
22
|
+
plugs in.
|
|
23
|
+
- [The spec](https://github.com/feincms/feincms3-api/blob/main/specs/api.md): the design and the reasoning behind it.
|
|
24
|
+
- [Issues](https://github.com/feincms/feincms3-api/issues): what's planned.
|
|
25
|
+
- [feincms3-api-cli](https://github.com/feincms/feincms3-api/blob/main/cli/README.md): the API from the command line
|
|
26
|
+
(`f3api`), for people and agents with a shell.
|
|
27
|
+
- [Translating](https://github.com/feincms/feincms3-api/blob/main/docs/translating.md) content over the API.
|
|
28
|
+
|
|
29
|
+
## Setup
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install feincms3-api
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
INSTALLED_APPS = [
|
|
37
|
+
...,
|
|
38
|
+
"feincms3_api",
|
|
39
|
+
]
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Register what the API exposes; nothing else is. Each model needs a
|
|
43
|
+
`ModelAdmin`, that's where the forms, permissions and plugins come from:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
# app/content_api.py
|
|
47
|
+
from feincms3_api.api import ContentAPI
|
|
48
|
+
from feincms3_api.cabinet import FileResource, FolderResource
|
|
49
|
+
from feincms3_api.forms import ConfiguredFormResource
|
|
50
|
+
from feincms3_api.resources import ObjectResource, PageResource, TreeResource
|
|
51
|
+
|
|
52
|
+
from app.articles.models import Article
|
|
53
|
+
from app.forms.models import Form
|
|
54
|
+
from app.pages.models import Page
|
|
55
|
+
|
|
56
|
+
content_api = ContentAPI()
|
|
57
|
+
content_api.register(PageResource(Page))
|
|
58
|
+
content_api.register(ObjectResource(Article))
|
|
59
|
+
content_api.register(ConfiguredFormResource(Form)) # feincms3-forms
|
|
60
|
+
content_api.register(FileResource()) # django-cabinet
|
|
61
|
+
content_api.register(FolderResource())
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Mount it, either as an API of its own or as a router in an existing
|
|
65
|
+
`NinjaAPI`:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
# app/urls.py
|
|
69
|
+
from app.content_api import content_api
|
|
70
|
+
|
|
71
|
+
urlpatterns = [
|
|
72
|
+
...,
|
|
73
|
+
path("api/content/", content_api.as_api().urls),
|
|
74
|
+
]
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`./manage.py migrate` creates the tables for tokens and uploads. The
|
|
78
|
+
interactive docs are at `api/content/docs`.
|
|
79
|
+
|
|
80
|
+
### Settings
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
FEINCMS3_API = {
|
|
84
|
+
# Never exposed: fields, or values inside JSON data
|
|
85
|
+
"EXCLUDE_FIELDS": [
|
|
86
|
+
"forms.form.recipient_email",
|
|
87
|
+
"pages.jsonplugin_key_figures.data.internal_note",
|
|
88
|
+
],
|
|
89
|
+
"DEFAULT_PAGE_SIZE": 50,
|
|
90
|
+
"MAX_PAGE_SIZE": 200,
|
|
91
|
+
"TOKEN_LIFETIME": timedelta(hours=8),
|
|
92
|
+
"UPLOAD_LIFETIME": timedelta(days=1),
|
|
93
|
+
"UPLOAD_STORAGE": "default",
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### The schema snapshot
|
|
98
|
+
|
|
99
|
+
`./manage.py f3api_schema app.content_api.content_api` prints every type
|
|
100
|
+
with its fields and what kind of value each is, as a superuser sees them.
|
|
101
|
+
Commit it and compare it in a test, so a new plugin or field becomes
|
|
102
|
+
visible through the API only after someone looked at the diff.
|
|
103
|
+
|
|
104
|
+
## Using it
|
|
105
|
+
|
|
106
|
+
Only active staff users can use the API, with their admin permissions.
|
|
107
|
+
Scripts and agents use tokens: staff users create their own in the admin
|
|
108
|
+
(the secret is shown once), or `./manage.py f3api_token USERNAME --write`
|
|
109
|
+
prints one. Tokens are read-only unless created for writing, and expire
|
|
110
|
+
after `TOKEN_LIFETIME`. `./manage.py f3api_cleanup` removes expired tokens
|
|
111
|
+
and uploads; run it daily.
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
API=https://example.com/api/content
|
|
115
|
+
AUTH="Authorization: Bearer f3api_…"
|
|
116
|
+
|
|
117
|
+
curl -H "$AUTH" $API/schema/ # what's there
|
|
118
|
+
curl -H "$AUTH" "$API/pages/find/?path=/de/angebot/"
|
|
119
|
+
curl -H "$AUTH" "$API/pages/17/?expand=references" # one page with its content
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Writes need the ETag of what was read (`If-Match`), and fail as a whole with
|
|
123
|
+
every problem and its path. `?dry_run=true` runs a write in a transaction
|
|
124
|
+
which is rolled back and returns what it would have done:
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
curl -X PUT -H "$AUTH" -H 'If-Match: "9f2c…"' -H "Content-Type: application/json" \
|
|
128
|
+
"$API/pages/17/content/?dry_run=true" \
|
|
129
|
+
-d '{"content": {"main": [
|
|
130
|
+
{"type": "pages.richtext", "fields": {"text": "<h2>Hello</h2>"}}
|
|
131
|
+
]}}'
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
**A dry run runs everything but the commit**, signal handlers included:
|
|
135
|
+
anything they do outside the database (sending mail, calling other APIs,
|
|
136
|
+
writing files) happens in a dry run too.
|
|
137
|
+
|
|
138
|
+
Files are uploaded first (`POST /uploads/`, multipart) and then named in a
|
|
139
|
+
write as `{"upload": "<id>"}`. Changes appear in the admin's history,
|
|
140
|
+
marked "(Through the API.)".
|
|
141
|
+
|
|
142
|
+
## Credits
|
|
143
|
+
|
|
144
|
+
feincms3-api grows out of feincms3-autotranslate, started by Moritz Wettstein
|
|
145
|
+
and Matthias Kestenholz at [Feinheit](https://www.feinheit.ch/) in October
|
|
146
|
+
2026. Its content introspection (which fields hold text, HTML or links, JSON
|
|
147
|
+
schemas, plugin discovery) is the base of this package.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1"
|
|
@@ -13,6 +13,7 @@ from ninja import NinjaAPI
|
|
|
13
13
|
|
|
14
14
|
from feincms3_api.adapters import AdapterRegistry
|
|
15
15
|
from feincms3_api.auth import default_auth
|
|
16
|
+
from feincms3_api.batch import BatchMixin
|
|
16
17
|
from feincms3_api.codecs import codecs as default_codecs
|
|
17
18
|
from feincms3_api.errors import NotFoundError
|
|
18
19
|
from feincms3_api.reading import ReadingMixin
|
|
@@ -23,7 +24,7 @@ from feincms3_api.writing import WritingMixin
|
|
|
23
24
|
_instances = []
|
|
24
25
|
|
|
25
26
|
|
|
26
|
-
class ContentAPI(ReadingMixin, SchemaMixin, WritingMixin):
|
|
27
|
+
class ContentAPI(ReadingMixin, SchemaMixin, WritingMixin, BatchMixin):
|
|
27
28
|
def __init__(self, *, auth=None, codecs=None, adapters=None):
|
|
28
29
|
self.auth = auth if auth is not None else default_auth()
|
|
29
30
|
self.codecs = codecs or default_codecs.copy()
|
|
@@ -36,7 +37,11 @@ class ContentAPI(ReadingMixin, SchemaMixin, WritingMixin):
|
|
|
36
37
|
def register(self, resource):
|
|
37
38
|
if "router" in self.__dict__:
|
|
38
39
|
raise RuntimeError("Register resources before using the router.")
|
|
39
|
-
if resource.name in self._resources or resource.name in {
|
|
40
|
+
if resource.name in self._resources or resource.name in {
|
|
41
|
+
"schema",
|
|
42
|
+
"uploads",
|
|
43
|
+
"batch",
|
|
44
|
+
}:
|
|
40
45
|
raise ValueError(f"The resource name {resource.name!r} is taken.")
|
|
41
46
|
self._resources[resource.name] = resource
|
|
42
47
|
return resource
|
|
@@ -51,6 +56,13 @@ class ContentAPI(ReadingMixin, SchemaMixin, WritingMixin):
|
|
|
51
56
|
except KeyError as exc:
|
|
52
57
|
raise NotFoundError(f"No resource {name!r}.") from exc
|
|
53
58
|
|
|
59
|
+
@cached_property
|
|
60
|
+
def components(self):
|
|
61
|
+
"""The OpenAPI schema's components, built when first requested"""
|
|
62
|
+
from feincms3_api.openapi import Components # noqa: PLC0415
|
|
63
|
+
|
|
64
|
+
return Components(self)
|
|
65
|
+
|
|
54
66
|
@cached_property
|
|
55
67
|
def router(self):
|
|
56
68
|
from feincms3_api.http import build_router # noqa: PLC0415
|
|
@@ -28,11 +28,13 @@ def _content_apis():
|
|
|
28
28
|
|
|
29
29
|
|
|
30
30
|
def check_resources(app_configs=None, **kwargs):
|
|
31
|
+
from feincms3_api.codecs import label # noqa: PLC0415
|
|
32
|
+
|
|
31
33
|
errors = []
|
|
32
34
|
for api in _content_apis():
|
|
33
35
|
for resource in api.resources:
|
|
34
36
|
try:
|
|
35
|
-
resource.model_admin
|
|
37
|
+
model_admin = resource.model_admin
|
|
36
38
|
except ImproperlyConfigured:
|
|
37
39
|
errors.append(
|
|
38
40
|
checks.Error(
|
|
@@ -42,6 +44,20 @@ def check_resources(app_configs=None, **kwargs):
|
|
|
42
44
|
id="feincms3_api.E001",
|
|
43
45
|
)
|
|
44
46
|
)
|
|
47
|
+
continue
|
|
48
|
+
# Plugins and other inlines are keyed by their model's type.
|
|
49
|
+
seen = set()
|
|
50
|
+
for inline in model_admin.inlines:
|
|
51
|
+
if (type_label := label(inline.model)) in seen:
|
|
52
|
+
errors.append(
|
|
53
|
+
checks.Error(
|
|
54
|
+
f"The admin of {resource.type} has more than one"
|
|
55
|
+
f" inline for {type_label}.",
|
|
56
|
+
hint="The API keys inlines by their model's type.",
|
|
57
|
+
id="feincms3_api.E003",
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
seen.add(type_label)
|
|
45
61
|
return errors
|
|
46
62
|
|
|
47
63
|
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Several writes in one transaction: ``POST /batch/``
|
|
3
|
+
|
|
4
|
+
The operations run in order through ``ContentAPI``'s operations, in one
|
|
5
|
+
transaction: all of them are saved, or none. ``{"ref": name}`` stands for
|
|
6
|
+
the id of an object created earlier in the batch, wherever an id goes.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from django.db import transaction
|
|
10
|
+
|
|
11
|
+
from feincms3_api.conf import config
|
|
12
|
+
from feincms3_api.errors import APIError, ValidationFailedError
|
|
13
|
+
from feincms3_api.writing import forget_ids
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
OPERATIONS = {
|
|
17
|
+
# op: (keys it needs, keys it may have)
|
|
18
|
+
"create": ({"resource"}, {"ref", "fields", "content", "inlines"}),
|
|
19
|
+
"update": ({"resource", "id"}, {"etag", "fields", "content", "inlines"}),
|
|
20
|
+
"replace_content": ({"resource", "id", "content"}, {"etag"}),
|
|
21
|
+
"update_plugin": ({"resource", "id", "plugin", "fields"}, {"etag"}),
|
|
22
|
+
"delete": ({"resource", "id"}, {"etag"}),
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class BatchError(APIError):
|
|
27
|
+
"""An operation's error, with the operation's index"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, index, exc):
|
|
30
|
+
super().__init__(exc.detail)
|
|
31
|
+
self.status = exc.status
|
|
32
|
+
self.index = index
|
|
33
|
+
self.exc = exc
|
|
34
|
+
|
|
35
|
+
def as_json(self):
|
|
36
|
+
data = self.exc.as_json()
|
|
37
|
+
if isinstance(self.exc, ValidationFailedError):
|
|
38
|
+
data["errors"] = [
|
|
39
|
+
error | {"path": _join(f"operations[{self.index}]", error["path"])}
|
|
40
|
+
for error in data["errors"]
|
|
41
|
+
]
|
|
42
|
+
return {"operation": self.index, **data}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _join(prefix, path):
|
|
46
|
+
if not prefix or not path:
|
|
47
|
+
return prefix or path
|
|
48
|
+
return f"{prefix}{path}" if path.startswith("[") else f"{prefix}.{path}"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class BatchMixin:
|
|
52
|
+
def batch(self, request, payload, *, dry_run=False):
|
|
53
|
+
"""
|
|
54
|
+
Run ``payload["operations"]`` in one transaction; returns each
|
|
55
|
+
operation's result (``None`` for deletions) and the ids of ``refs``
|
|
56
|
+
"""
|
|
57
|
+
operations = _check(payload)
|
|
58
|
+
refs, created, written, results = {}, [], set(), []
|
|
59
|
+
with transaction.atomic():
|
|
60
|
+
for index, given in enumerate(operations):
|
|
61
|
+
try:
|
|
62
|
+
operation = _resolve(given, refs, "")
|
|
63
|
+
result = self._run(request, operation, written, created)
|
|
64
|
+
except APIError as exc:
|
|
65
|
+
raise BatchError(index, exc) from exc
|
|
66
|
+
if operation["op"] == "create":
|
|
67
|
+
written.add((operation["resource"], str(result["id"])))
|
|
68
|
+
if "ref" in operation:
|
|
69
|
+
refs[operation["ref"]] = result["id"]
|
|
70
|
+
elif operation["op"] != "delete":
|
|
71
|
+
written.add((operation["resource"], str(operation["id"])))
|
|
72
|
+
results.append(result)
|
|
73
|
+
if dry_run:
|
|
74
|
+
transaction.set_rollback(True)
|
|
75
|
+
for result in results:
|
|
76
|
+
if result is not None:
|
|
77
|
+
forget_ids(result, created)
|
|
78
|
+
refs = dict.fromkeys(refs)
|
|
79
|
+
return {"results": results, "refs": refs}
|
|
80
|
+
|
|
81
|
+
def _run(self, request, operation, written, created):
|
|
82
|
+
op, name = operation["op"], operation["resource"]
|
|
83
|
+
if op == "create":
|
|
84
|
+
return self.create(
|
|
85
|
+
request, name, _body(operation, "create"), created=created
|
|
86
|
+
)
|
|
87
|
+
pk = operation["id"]
|
|
88
|
+
# What the batch wrote already can't have changed since
|
|
89
|
+
if_match = operation.get("etag") or (
|
|
90
|
+
"*" if (name, str(pk)) in written else None
|
|
91
|
+
)
|
|
92
|
+
if op == "update":
|
|
93
|
+
return self.update(
|
|
94
|
+
request,
|
|
95
|
+
name,
|
|
96
|
+
pk,
|
|
97
|
+
_body(operation, "update"),
|
|
98
|
+
if_match=if_match,
|
|
99
|
+
created=created,
|
|
100
|
+
)
|
|
101
|
+
if op == "replace_content":
|
|
102
|
+
return self.replace_content(
|
|
103
|
+
request,
|
|
104
|
+
name,
|
|
105
|
+
pk,
|
|
106
|
+
operation["content"],
|
|
107
|
+
if_match=if_match,
|
|
108
|
+
created=created,
|
|
109
|
+
)
|
|
110
|
+
if op == "update_plugin":
|
|
111
|
+
return self.update_plugin(
|
|
112
|
+
request,
|
|
113
|
+
name,
|
|
114
|
+
pk,
|
|
115
|
+
operation["plugin"]["type"],
|
|
116
|
+
operation["plugin"]["id"],
|
|
117
|
+
{"fields": operation["fields"]},
|
|
118
|
+
if_match=if_match,
|
|
119
|
+
)
|
|
120
|
+
self.delete(request, name, pk, if_match=if_match)
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _body(operation, op):
|
|
125
|
+
return {
|
|
126
|
+
key: operation[key]
|
|
127
|
+
for key in ("fields", "content", "inlines")
|
|
128
|
+
if key in operation
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _check(payload):
|
|
133
|
+
"""The operations, or every problem with their shape"""
|
|
134
|
+
if not isinstance(payload, dict) or not isinstance(
|
|
135
|
+
operations := payload.get("operations"), list
|
|
136
|
+
):
|
|
137
|
+
raise ValidationFailedError(
|
|
138
|
+
[{"path": "operations", "message": "Expected a list of operations."}]
|
|
139
|
+
)
|
|
140
|
+
if len(operations) > (limit := config()["MAX_BATCH_OPERATIONS"]):
|
|
141
|
+
raise ValidationFailedError(
|
|
142
|
+
[{"path": "operations", "message": f"At most {limit} operations."}]
|
|
143
|
+
)
|
|
144
|
+
errors, names = [], set()
|
|
145
|
+
for index, operation in enumerate(operations):
|
|
146
|
+
path = f"operations[{index}]"
|
|
147
|
+
if not isinstance(operation, dict):
|
|
148
|
+
errors.append({"path": path, "message": "Expected an object."})
|
|
149
|
+
continue
|
|
150
|
+
if (op := operation.get("op")) not in OPERATIONS:
|
|
151
|
+
errors.append(
|
|
152
|
+
{
|
|
153
|
+
"path": f"{path}.op",
|
|
154
|
+
"message": f"One of {', '.join(OPERATIONS)}.",
|
|
155
|
+
}
|
|
156
|
+
)
|
|
157
|
+
continue
|
|
158
|
+
needed, optional = OPERATIONS[op]
|
|
159
|
+
errors.extend(
|
|
160
|
+
{"path": f"{path}.{key}", "message": "Missing."}
|
|
161
|
+
for key in sorted(needed - set(operation))
|
|
162
|
+
)
|
|
163
|
+
errors.extend(
|
|
164
|
+
{"path": f"{path}.{key}", "message": "Unknown key."}
|
|
165
|
+
for key in sorted(set(operation) - needed - optional - {"op"})
|
|
166
|
+
)
|
|
167
|
+
if "ref" in operation:
|
|
168
|
+
if not isinstance(ref := operation["ref"], str) or not ref:
|
|
169
|
+
errors.append({"path": f"{path}.ref", "message": "Expected a name."})
|
|
170
|
+
elif ref in names:
|
|
171
|
+
errors.append(
|
|
172
|
+
{"path": f"{path}.ref", "message": "Used earlier in the batch."}
|
|
173
|
+
)
|
|
174
|
+
names.add(ref)
|
|
175
|
+
plugin = operation.get("plugin")
|
|
176
|
+
if "plugin" in operation and not (
|
|
177
|
+
isinstance(plugin, dict) and set(plugin) == {"type", "id"}
|
|
178
|
+
):
|
|
179
|
+
errors.append(
|
|
180
|
+
{
|
|
181
|
+
"path": f"{path}.plugin",
|
|
182
|
+
"message": 'Expected {"type": …, "id": …}.',
|
|
183
|
+
}
|
|
184
|
+
)
|
|
185
|
+
if errors:
|
|
186
|
+
raise ValidationFailedError(errors)
|
|
187
|
+
return operations
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _resolve(value, refs, path):
|
|
191
|
+
"""``value`` with ``{"ref": name}`` replaced by the id of ``name``"""
|
|
192
|
+
if isinstance(value, dict):
|
|
193
|
+
if set(value) == {"ref"} and isinstance(value["ref"], str):
|
|
194
|
+
if value["ref"] not in refs:
|
|
195
|
+
raise ValidationFailedError(
|
|
196
|
+
[
|
|
197
|
+
{
|
|
198
|
+
"path": path,
|
|
199
|
+
"message": f"No object {value['ref']!r} was"
|
|
200
|
+
" created earlier in the batch.",
|
|
201
|
+
}
|
|
202
|
+
]
|
|
203
|
+
)
|
|
204
|
+
return refs[value["ref"]]
|
|
205
|
+
return {
|
|
206
|
+
key: item if key == "ref" else _resolve(item, refs, _join(path, key))
|
|
207
|
+
for key, item in value.items()
|
|
208
|
+
}
|
|
209
|
+
if isinstance(value, list):
|
|
210
|
+
return [_resolve(item, refs, f"{path}[{i}]") for i, item in enumerate(value)]
|
|
211
|
+
return value
|
|
@@ -49,6 +49,7 @@ except ImportError: # pragma: no cover
|
|
|
49
49
|
|
|
50
50
|
KIND = "x-feincms3-kind"
|
|
51
51
|
REF = "x-feincms3-ref"
|
|
52
|
+
HTML_ALLOWED = "x-feincms3-html"
|
|
52
53
|
|
|
53
54
|
|
|
54
55
|
def label(model):
|
|
@@ -154,7 +155,44 @@ class HTMLCodec(CharCodec):
|
|
|
154
155
|
kind = HTML
|
|
155
156
|
|
|
156
157
|
def json_schema(self, field):
|
|
157
|
-
|
|
158
|
+
schema = {**super().json_schema(field), "contentMediaType": "text/html"}
|
|
159
|
+
if (allowed := allowed_html(field)) is not None:
|
|
160
|
+
schema[HTML_ALLOWED] = allowed
|
|
161
|
+
return schema
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def allowed_html(field):
|
|
165
|
+
"""
|
|
166
|
+
The markup a django-prose-editor field allows, from its extensions, as
|
|
167
|
+
nh3's allowlist (``tags``, ``attributes``, ``url_schemes``, …), and
|
|
168
|
+
whether the form or model field removes everything else
|
|
169
|
+
(``sanitize=True``); ``None`` for fields without extensions
|
|
170
|
+
(prose-editor's legacy mode)
|
|
171
|
+
"""
|
|
172
|
+
form_field = field.form_field
|
|
173
|
+
extensions = (getattr(form_field, "config", None) or {}).get("extensions")
|
|
174
|
+
if extensions is None:
|
|
175
|
+
return None
|
|
176
|
+
from django_prose_editor import fields # noqa: PLC0415
|
|
177
|
+
from django_prose_editor.config import allowlist_from_extensions # noqa: PLC0415
|
|
178
|
+
|
|
179
|
+
allowed = {}
|
|
180
|
+
for key, value in allowlist_from_extensions(extensions).items():
|
|
181
|
+
if isinstance(value, set | frozenset | list | tuple):
|
|
182
|
+
allowed[key] = sorted(value)
|
|
183
|
+
elif isinstance(value, dict):
|
|
184
|
+
allowed[key] = {tag: sorted(items) for tag, items in sorted(value.items())}
|
|
185
|
+
# Without sanitising, prose-editor only drops empty paragraphs.
|
|
186
|
+
passing = {
|
|
187
|
+
getattr(fields, "_identity", None),
|
|
188
|
+
getattr(fields, "_actually_empty", None),
|
|
189
|
+
}
|
|
190
|
+
allowed["sanitized"] = any(
|
|
191
|
+
getattr(f, "sanitize", None) not in passing
|
|
192
|
+
for f in (form_field, field.model_field)
|
|
193
|
+
if hasattr(f, "sanitize")
|
|
194
|
+
)
|
|
195
|
+
return allowed
|
|
158
196
|
|
|
159
197
|
|
|
160
198
|
class BooleanCodec(Codec):
|