tortoise-orm-studio 1.0.0__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.
Files changed (68) hide show
  1. tortoise_orm_studio/__init__.py +11 -0
  2. tortoise_orm_studio/adapters/__init__.py +1 -0
  3. tortoise_orm_studio/adapters/aiohttp_adapter.py +31 -0
  4. tortoise_orm_studio/adapters/asgi.py +89 -0
  5. tortoise_orm_studio/adapters/base.py +25 -0
  6. tortoise_orm_studio/adapters/django_adapter.py +84 -0
  7. tortoise_orm_studio/adapters/quart_adapter.py +32 -0
  8. tortoise_orm_studio/adapters/registry.py +39 -0
  9. tortoise_orm_studio/adapters/sanic_adapter.py +39 -0
  10. tortoise_orm_studio/auth.py +34 -0
  11. tortoise_orm_studio/cli.py +41 -0
  12. tortoise_orm_studio/core/__init__.py +1 -0
  13. tortoise_orm_studio/core/aerich.py +86 -0
  14. tortoise_orm_studio/core/ai.py +87 -0
  15. tortoise_orm_studio/core/audit.py +69 -0
  16. tortoise_orm_studio/core/config.py +58 -0
  17. tortoise_orm_studio/core/filters.py +94 -0
  18. tortoise_orm_studio/core/handler.py +249 -0
  19. tortoise_orm_studio/core/http.py +55 -0
  20. tortoise_orm_studio/core/i18n.py +18 -0
  21. tortoise_orm_studio/core/introspect.py +197 -0
  22. tortoise_orm_studio/core/manifest.py +128 -0
  23. tortoise_orm_studio/core/pagination.py +59 -0
  24. tortoise_orm_studio/core/permissions.py +46 -0
  25. tortoise_orm_studio/core/plugins.py +214 -0
  26. tortoise_orm_studio/core/ratelimit.py +32 -0
  27. tortoise_orm_studio/core/scoping.py +23 -0
  28. tortoise_orm_studio/core/serializers.py +61 -0
  29. tortoise_orm_studio/core/service.py +594 -0
  30. tortoise_orm_studio/plugins.py +8 -0
  31. tortoise_orm_studio/static/ALPINE_LICENSE.txt +11 -0
  32. tortoise_orm_studio/static/_types.d.ts +706 -0
  33. tortoise_orm_studio/static/a11y.js +115 -0
  34. tortoise_orm_studio/static/ai.js +66 -0
  35. tortoise_orm_studio/static/alpine.min.js +23 -0
  36. tortoise_orm_studio/static/app.css +514 -0
  37. tortoise_orm_studio/static/app.js +1443 -0
  38. tortoise_orm_studio/static/audit.js +171 -0
  39. tortoise_orm_studio/static/copy-as.js +118 -0
  40. tortoise_orm_studio/static/er-layout.js +227 -0
  41. tortoise_orm_studio/static/er.js +296 -0
  42. tortoise_orm_studio/static/filters.js +114 -0
  43. tortoise_orm_studio/static/i18n.en.js +190 -0
  44. tortoise_orm_studio/static/i18n.js +140 -0
  45. tortoise_orm_studio/static/i18n.zh-CN.js +189 -0
  46. tortoise_orm_studio/static/index.html +515 -0
  47. tortoise_orm_studio/static/inline-edit.js +107 -0
  48. tortoise_orm_studio/static/json-view.js +161 -0
  49. tortoise_orm_studio/static/migrations.js +139 -0
  50. tortoise_orm_studio/static/palette.js +141 -0
  51. tortoise_orm_studio/static/pending.js +240 -0
  52. tortoise_orm_studio/static/pickers.js +230 -0
  53. tortoise_orm_studio/static/playground.js +105 -0
  54. tortoise_orm_studio/static/query-history.js +84 -0
  55. tortoise_orm_studio/static/shortcuts.js +145 -0
  56. tortoise_orm_studio/static/state-hash.js +112 -0
  57. tortoise_orm_studio/static/tabs.js +368 -0
  58. tortoise_orm_studio/static/theme-init.js +33 -0
  59. tortoise_orm_studio/static/theme.js +106 -0
  60. tortoise_orm_studio/static/toasts.js +76 -0
  61. tortoise_orm_studio/static/views.js +70 -0
  62. tortoise_orm_studio/static/widgets.js +345 -0
  63. tortoise_orm_studio/studio.py +51 -0
  64. tortoise_orm_studio-1.0.0.dist-info/METADATA +177 -0
  65. tortoise_orm_studio-1.0.0.dist-info/RECORD +68 -0
  66. tortoise_orm_studio-1.0.0.dist-info/WHEEL +4 -0
  67. tortoise_orm_studio-1.0.0.dist-info/entry_points.txt +2 -0
  68. tortoise_orm_studio-1.0.0.dist-info/licenses/LICENSE +13 -0
@@ -0,0 +1,69 @@
1
+ """Built-in audit log — a Tortoise model plus a ready-made hook.
2
+
3
+ Two opt-in steps for users:
4
+
5
+ # 1. Register the model
6
+ TORTOISE_ORM = {
7
+ "apps": {"models": {
8
+ "models": ["models", "tortoise_orm_studio.core.audit"],
9
+ "default_connection": "default",
10
+ }},
11
+ ...
12
+ }
13
+
14
+ # 2. Use the hook
15
+ from tortoise_orm_studio import Studio
16
+ from tortoise_orm_studio.core.audit import hook as audit_hook
17
+ studio = Studio(read_only=False, audit=audit_hook)
18
+
19
+ ``GET /api/audit`` reads back the log if the model is registered and the
20
+ table exists. Otherwise it returns ``{"available": false}`` with no error.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ from typing import Any, Dict
25
+
26
+ from tortoise import fields, models
27
+
28
+
29
+ class StudioAudit(models.Model):
30
+ """One row per audited action. Registered when the user opts in."""
31
+
32
+ id = fields.IntField(pk=True)
33
+ action = fields.CharField(max_length=32, index=True) # create|update|delete|m2m_add|m2m_remove
34
+ model = fields.CharField(max_length=200, index=True) # e.g. "models.Author"
35
+ object_pk = fields.CharField(max_length=200, null=True) # the pk of the audited row
36
+ before = fields.JSONField(null=True)
37
+ after = fields.JSONField(null=True)
38
+ actor = fields.CharField(max_length=200, null=True, index=True)
39
+ at = fields.DatetimeField(auto_now_add=True, index=True)
40
+
41
+ class Meta:
42
+ table = "studio_audit"
43
+
44
+ def __str__(self) -> str:
45
+ return f"{self.action} {self.model} {self.object_pk}"
46
+
47
+
48
+ async def hook(event: Dict[str, Any]) -> None:
49
+ """Async audit hook — pass as ``Studio(audit=hook)``.
50
+
51
+ Silently swallows DB errors: audit failures must never block the write
52
+ they're recording. Worst case: a missing log entry, never a failed save.
53
+ """
54
+ try:
55
+ await StudioAudit.create(
56
+ action=event.get("action", "unknown"),
57
+ model=event.get("model", ""),
58
+ object_pk=str(event["pk"]) if event.get("pk") is not None else None,
59
+ before=event.get("before"),
60
+ after=event.get("after"),
61
+ actor=event.get("actor"),
62
+ )
63
+ except Exception:
64
+ pass
65
+
66
+
67
+ def make_hook() -> Any:
68
+ """Return a fresh copy of the hook (useful for tests)."""
69
+ return hook
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Awaitable, Callable, Dict, List, Optional, Set, Tuple, Union
5
+
6
+ from .i18n import DEFAULT_LOCALE, LOCALES
7
+ from .plugins import StudioPlugin
8
+
9
+ AuthHook = Callable[[Any], Union[bool, Awaitable[bool]]] # (StudioRequest) -> bool
10
+ AuditHook = Callable[[Dict[str, Any]], Awaitable[None]]
11
+
12
+
13
+ @dataclass
14
+ class ModelConfig:
15
+ list_display: Optional[List[str]] = None
16
+ search_fields: Optional[List[str]] = None
17
+ readonly_fields: List[str] = field(default_factory=list)
18
+ exclude: List[str] = field(default_factory=list) # hidden everywhere (e.g. password_hash)
19
+
20
+
21
+ @dataclass
22
+ class StudioConfig:
23
+ read_only: bool = True
24
+ auth: Optional[AuthHook] = None
25
+ allow_remote: bool = False # only meaningful when auth is None
26
+ allow_models: Optional[Set[str]] = None # e.g. {"models.User"}; None = all
27
+ deny_models: Set[str] = field(default_factory=set)
28
+ default_page_size: int = 25
29
+ max_page_size: int = 200
30
+ max_export_rows: int = 10000
31
+ max_bulk: int = 500
32
+ max_batch: int = 500 # v0.5.0 - max ops in POST /api/v1/batch
33
+ audit: Optional[AuditHook] = None
34
+ migrations_dir: Optional[str] = None # Aerich migrations directory; auto-detected if None
35
+ model_cfg: Dict[type, ModelConfig] = field(default_factory=dict)
36
+ # v0.4.0 — host-supplied policy hooks. Kept as Any to avoid import cycles.
37
+ permissions: Any = None
38
+ scope: Any = None
39
+ rate_limiter: Any = None
40
+ cursor_secret: str = "tortoise-orm-studio" # override in production
41
+ # v0.5.0 - optional host-supplied AI filter hook. Studio ships no model,
42
+ # key or AI dependency; the callable returns the model's raw text.
43
+ ai_filter: Any = None
44
+ ai_timeout: float = 10.0
45
+ ai_max_prompt: int = 2000
46
+ # v0.9.0 — host-supplied plugins, validated once by PluginManager.
47
+ plugins: Tuple[StudioPlugin, ...] = ()
48
+ # v0.9.0 — initial UI locale; the browser stores an explicit user choice.
49
+ locale: str = DEFAULT_LOCALE
50
+ locales: Tuple[str, ...] = LOCALES
51
+
52
+ def cfg_for(self, model: type) -> ModelConfig:
53
+ return self.model_cfg.get(model, ModelConfig())
54
+
55
+ def is_allowed(self, key: str) -> bool:
56
+ if key in self.deny_models:
57
+ return False
58
+ return self.allow_models is None or key in self.allow_models
@@ -0,0 +1,94 @@
1
+ """Whitelisted translation of UI filters / search / sort into Tortoise Q objects."""
2
+ from __future__ import annotations
3
+
4
+ from functools import reduce
5
+ from typing import Any, Dict, List, Optional, Tuple
6
+
7
+ from tortoise.expressions import Q
8
+
9
+ from .http import StudioError
10
+ from .serializers import from_json
11
+
12
+ COMPARE = {"gt", "gte", "lt", "lte"}
13
+ TEXT = {"contains", "icontains", "startswith", "istartswith", "endswith", "iendswith"}
14
+ OPS = {"eq", "ne", "in", "isnull"} | COMPARE | TEXT
15
+ TEXT_KINDS = {"string", "text", "enum"}
16
+ UNFILTERABLE = {"json", "binary"}
17
+
18
+
19
+ def _lookup(field: str, op: str) -> str:
20
+ """Q kwarg. 'author.name' + 'icontains' → 'author__name__icontains'."""
21
+ base = field if op in ("eq", "ne") else f"{field}__{op}"
22
+ return base.replace(".", "__")
23
+
24
+
25
+ def _resolve(desc: Dict[str, Any], name: str, err_code: str) -> Dict[str, Any]:
26
+ """Look up a field by name (plain or dotted traversal). Raises StudioError."""
27
+ if "." in name:
28
+ paths = desc.get("filter_paths", {})
29
+ info = paths.get(name)
30
+ if info is None:
31
+ raise StudioError(400, err_code, f"Unknown field: {name}")
32
+ return info
33
+ f = next((x for x in desc["fields"] if x["name"] == name), None)
34
+ if f is None:
35
+ raise StudioError(400, err_code, f"Unknown field: {name}")
36
+ return f
37
+
38
+
39
+ def build_query(desc: Dict[str, Any], enums: Dict[str, Any], filters: List[Dict[str, Any]],
40
+ search: Optional[str], sort: Optional[str]) -> Dict[str, Any]:
41
+ fields = {f["name"]: f for f in desc["fields"]}
42
+ conds: List[Tuple[str, Any, bool]] = []
43
+
44
+ for item in filters:
45
+ name = item.get("field")
46
+ op = item.get("op", "eq")
47
+ raw = item.get("value")
48
+ if not isinstance(name, str) or not name:
49
+ raise StudioError(400, "bad_filter", "filter needs 'field'")
50
+ f = _resolve(desc, name, "bad_filter")
51
+
52
+ if op not in OPS:
53
+ raise StudioError(400, "bad_filter", f"Unknown operator: {op}")
54
+ if f["kind"] in UNFILTERABLE and op != "isnull":
55
+ raise StudioError(400, "bad_filter", f"Cannot filter {f['kind']} field {name}")
56
+ if op in TEXT and f["kind"] not in TEXT_KINDS:
57
+ raise StudioError(400, "bad_filter", f"Operator {op} needs a text field")
58
+
59
+ if op == "isnull":
60
+ value: Any = bool(raw)
61
+ elif op == "in":
62
+ if not isinstance(raw, list):
63
+ raise StudioError(400, "bad_filter", "'in' needs a list value")
64
+ value = [from_json(f["kind"], v, enums.get(name)) for v in raw]
65
+ elif op in TEXT:
66
+ value = str(raw)
67
+ else:
68
+ value = from_json(f["kind"], raw, enums.get(name))
69
+
70
+ conds.append((_lookup(name, op), value, op == "ne"))
71
+
72
+ parts = [(~Q(**{lk: v}) if neg else Q(**{lk: v})) for lk, v, neg in conds]
73
+ code = [("~" if neg else "") + f"Q({lk}={v!r})" for lk, v, neg in conds]
74
+
75
+ if search:
76
+ sf = [n for n in desc.get("search_fields", []) if n in fields]
77
+ if sf:
78
+ parts.append(reduce(lambda a, b: a | b, [Q(**{f"{n}__icontains": search}) for n in sf]))
79
+ code.append("(" + " | ".join(f"Q({n}__icontains={search!r})" for n in sf) + ")")
80
+
81
+ order: List[str] = []
82
+ for token in filter(None, (sort or "").split(",")):
83
+ name = token.lstrip("-")
84
+ f = _resolve(desc, name, "bad_sort")
85
+ if f["kind"] in UNFILTERABLE:
86
+ raise StudioError(400, "bad_sort", f"Cannot sort by {token}")
87
+ prefix = "-" if token.startswith("-") else ""
88
+ order.append(prefix + name.replace(".", "__"))
89
+
90
+ return {
91
+ "q": reduce(lambda a, b: a & b, parts) if parts else None,
92
+ "order": order,
93
+ "code": " & ".join(code),
94
+ }
@@ -0,0 +1,249 @@
1
+ """The one place that knows routes, auth and error mapping. Adapters just call handle()."""
2
+ from __future__ import annotations
3
+
4
+ import inspect
5
+ import json
6
+ import logging
7
+ import re
8
+ import time
9
+ from dataclasses import replace
10
+ from typing import Any, Dict, List, Pattern, Tuple
11
+ from urllib.parse import urlparse
12
+
13
+ from tortoise.exceptions import BaseORMException, DoesNotExist, IntegrityError
14
+
15
+ from .config import StudioConfig
16
+ from .http import StudioError, StudioRequest, StudioResponse, error_response, json_response
17
+ from .manifest import MANIFEST
18
+ from .plugins import EMPTY, PluginManager
19
+ from .service import StudioService
20
+
21
+ log = logging.getLogger("tortoise_orm_studio")
22
+
23
+ LOOPBACK = {"127.0.0.1", "::1", "localhost"}
24
+
25
+ M = r"(?P<m>[^/]+)"
26
+ _ROUTES: List[Tuple[str, str, str]] = [
27
+ ("GET", r"/api/health", "health"),
28
+ ("GET", r"/api/schema", "schema"),
29
+ ("GET", r"/api/er", "er"),
30
+ ("GET", r"/api/connections", "connections"),
31
+ ("GET", r"/api/migrations", "migrations"),
32
+ ("GET", r"/api/migrations/pending", "migrations_pending"),
33
+ ("GET", r"/api/audit", "audit_log"),
34
+ ("POST", r"/api/query/preview", "preview"),
35
+ ("POST", r"/api/batch", "batch"),
36
+ ("POST", r"/api/ai/filter", "ai_filter"),
37
+ ("GET", rf"/api/models/{M}", "list"),
38
+ ("POST", rf"/api/models/{M}", "create"),
39
+ ("GET", rf"/api/models/{M}/export", "export"),
40
+ ("GET", rf"/api/models/{M}/pydantic", "pydantic"),
41
+ ("POST", rf"/api/models/{M}/bulk-delete", "bulk_delete"),
42
+ ("GET", rf"/api/models/{M}/(?P<pk>[^/]+)", "get"),
43
+ ("PATCH", rf"/api/models/{M}/(?P<pk>[^/]+)", "update"),
44
+ ("DELETE", rf"/api/models/{M}/(?P<pk>[^/]+)", "delete"),
45
+ ("GET", rf"/api/models/{M}/(?P<pk>[^/]+)/(?P<rel>[^/]+)", "related"),
46
+ ("POST", rf"/api/models/{M}/(?P<pk>[^/]+)/(?P<rel>[^/]+)", "m2m_add"),
47
+ ("DELETE", rf"/api/models/{M}/(?P<pk>[^/]+)/(?P<rel>[^/]+)", "m2m_remove"),
48
+ ]
49
+
50
+ #: (method, compiled pattern, route handler suffix). Compiled once at import.
51
+ ROUTES: List[Tuple[str, Pattern[str], str]] = [
52
+ (m, re.compile(p + r"$"), n) for m, p, n in _ROUTES
53
+ ]
54
+
55
+
56
+ class StudioHandler:
57
+ def __init__(self, service: StudioService, config: StudioConfig, plugins: PluginManager = EMPTY):
58
+ self.service, self.config, self.plugins = service, config, plugins
59
+
60
+ async def handle(self, req: StudioRequest) -> StudioResponse:
61
+ started = time.monotonic()
62
+ try:
63
+ resp = await self._dispatch(req)
64
+ except StudioError as e:
65
+ resp = error_response(e)
66
+ except DoesNotExist as e:
67
+ resp = error_response(StudioError(404, "not_found", str(e)))
68
+ except IntegrityError as e:
69
+ resp = error_response(StudioError(409, "integrity_error", str(e)))
70
+ except (ValueError, KeyError, TypeError, BaseORMException) as e: # JSON errors are ValueErrors
71
+ resp = error_response(StudioError(400, "bad_request", str(e)))
72
+ except Exception:
73
+ log.exception("studio internal error")
74
+ resp = error_response(StudioError(500, "internal", "Internal error"))
75
+ # Structured access log: NEVER include the body, query values, headers
76
+ # or row data — only the route shape, status and timing.
77
+ log.info("studio request method=%s path=%s status=%s ms=%.1f",
78
+ req.method, req.path, resp.status, (time.monotonic() - started) * 1000)
79
+ resp.headers.update({"x-content-type-options": "nosniff", "cache-control": "no-store",
80
+ "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; "
81
+ "img-src 'self' data:; frame-ancestors 'none'"})
82
+ return resp
83
+
84
+ async def _guard(self, req: StudioRequest) -> None:
85
+ cfg = self.config
86
+ if cfg.rate_limiter is not None:
87
+ cfg.rate_limiter.check(req.client or "unknown")
88
+ if cfg.auth is not None:
89
+ ok = cfg.auth(req)
90
+ if inspect.isawaitable(ok):
91
+ ok = await ok
92
+ if not ok:
93
+ raise StudioError(401, "unauthorized", "Authentication required",
94
+ {"www-authenticate": 'Basic realm="tortoise-orm-studio"'})
95
+ elif not cfg.allow_remote:
96
+ proxied = "x-forwarded-for" in req.headers or "forwarded" in req.headers
97
+ if req.client not in LOOPBACK or proxied:
98
+ raise StudioError(403, "forbidden", "Localhost only. Pass auth=... or allow_remote=True.")
99
+ if req.method != "GET":
100
+ if req.headers.get("x-requested-with") != "studio":
101
+ raise StudioError(403, "csrf", "Missing X-Requested-With: studio header")
102
+ origin = req.headers.get("origin")
103
+ if origin and urlparse(origin).netloc != req.headers.get("host", ""):
104
+ raise StudioError(403, "csrf", "Cross-origin write blocked")
105
+
106
+ async def _dispatch(self, req: StudioRequest) -> StudioResponse:
107
+ await self._guard(req)
108
+ # `/api/v1` is the stable public prefix; `/api` stays as a deprecated
109
+ # alias. Normalise once here so the route table and every adapter see
110
+ # exactly one canonical path (no duplicated routes to drift).
111
+ path = req.path
112
+ if path == "/api/v1":
113
+ path = "/api"
114
+ elif path.startswith("/api/v1/"):
115
+ path = "/api" + path[len("/api/v1"):]
116
+ if req.method == "GET":
117
+ asset = MANIFEST.read(path)
118
+ if asset is not None:
119
+ entry, body = asset
120
+ return StudioResponse(200, {"content-type": entry.content_type}, body)
121
+ for method, rx, name in ROUTES:
122
+ match = rx.match(path) if method == req.method else None
123
+ if match:
124
+ return await getattr(self, "r_" + name)(req, **match.groupdict())
125
+ # v0.9.0 — plugins are dispatched here, after the shared guard, so
126
+ # auth/CSRF/rate limits still apply and built-in routes always win.
127
+ found = self.plugins.match(req.method, path)
128
+ if found:
129
+ handler, groups = found
130
+ # Plugins see the canonical path so /api and /api/v1 behave the
131
+ # same; the original request object is left untouched.
132
+ return await self.plugins.dispatch(handler, replace(req, path=path), groups)
133
+ raise StudioError(404, "not_found", "No such route")
134
+
135
+ # ---------- helpers
136
+ def _page(self, req: StudioRequest) -> Dict[str, Any]:
137
+ return {"page": int(req.q("page") or "1"), "limit": int(req.q("limit") or "0") or None}
138
+
139
+ def _filters(self, req: StudioRequest) -> List[Dict[str, Any]]:
140
+ data = json.loads(req.q("filter") or "[]")
141
+ if not isinstance(data, list) or not all(isinstance(i, dict) for i in data):
142
+ raise StudioError(400, "bad_filter", "filter must be a JSON list of objects")
143
+ return data
144
+
145
+ def _actor(self, req: StudioRequest) -> Any:
146
+ return req.state.get("user")
147
+
148
+ # ---------- routes
149
+ async def r_health(self, req):
150
+ return json_response({"ok": True, "read_only": self.config.read_only})
151
+
152
+ async def r_schema(self, req):
153
+ schema = self.service.schema()
154
+ schema["plugins"] = self.plugins.describe()
155
+ schema["locale"] = self.config.locale
156
+ schema["locales"] = list(self.config.locales)
157
+ return json_response(schema)
158
+
159
+ async def r_er(self, req):
160
+ return json_response(self.service.er())
161
+
162
+ async def r_connections(self, req):
163
+ return json_response({"connections": self.service.schema()["connections"]})
164
+
165
+ async def r_migrations(self, req):
166
+ return json_response(await self.service.migrations())
167
+
168
+ async def r_migrations_pending(self, req):
169
+ """Pending migrations only; keeps the full view stable for older UIs."""
170
+ full = await self.service.migrations()
171
+ return json_response({
172
+ "pending": full["pending"],
173
+ "available": full["available"],
174
+ "connection": full["connection"],
175
+ })
176
+
177
+ async def r_audit_log(self, req):
178
+ return json_response(await self.service.audit_log(
179
+ page=int(req.q("page") or "1"),
180
+ limit=int(req.q("limit") or 0) or None,
181
+ model=req.q("model"),
182
+ action=req.q("action"),
183
+ actor=req.q("actor"),
184
+ since=req.q("since"),
185
+ until=req.q("until"),
186
+ conn=req.q("connection"),
187
+ ))
188
+
189
+ async def r_preview(self, req):
190
+ b = req.json()
191
+ return json_response(self.service.preview(b["model"], b.get("filters", []), b.get("search"),
192
+ b.get("sort"), b.get("limit", 50)))
193
+
194
+ async def r_batch(self, req):
195
+ b = req.json()
196
+ if isinstance(b, dict):
197
+ ops = b.get("operations")
198
+ conn = b.get("connection") or req.q("connection")
199
+ else:
200
+ ops, conn = b, req.q("connection")
201
+ return json_response(await self.service.batch(ops, conn, self._actor(req)))
202
+
203
+ async def r_ai_filter(self, req):
204
+ b = req.json()
205
+ return json_response(await self.service.ai_filter(b.get("model"), b.get("text")))
206
+
207
+ async def r_list(self, req, m):
208
+ return json_response(await self.service.list(m, sort=req.q("sort"), filters=self._filters(req),
209
+ search=req.q("search"), conn=req.q("connection"),
210
+ after=req.q("after"), before=req.q("before"),
211
+ **self._page(req)))
212
+
213
+ async def r_create(self, req, m):
214
+ return json_response(await self.service.create(m, req.json(), req.q("connection"), self._actor(req)), 201)
215
+
216
+ async def r_export(self, req, m):
217
+ ctype, body = await self.service.export(m, req.q("format", "csv"), req.q("sort"), self._filters(req),
218
+ req.q("search"), req.q("connection"))
219
+ ext = "json" if "json" in ctype else "csv"
220
+ return StudioResponse(200, {"content-type": ctype,
221
+ "content-disposition": f'attachment; filename="{m}.{ext}"'}, body)
222
+
223
+ async def r_pydantic(self, req, m):
224
+ return json_response(self.service.pydantic(m))
225
+
226
+ async def r_bulk_delete(self, req, m):
227
+ n = await self.service.bulk_delete(m, req.json()["ids"], req.q("connection"), self._actor(req))
228
+ return json_response({"deleted": n})
229
+
230
+ async def r_get(self, req, m, pk):
231
+ return json_response(await self.service.get(m, pk, req.q("connection")))
232
+
233
+ async def r_update(self, req, m, pk):
234
+ return json_response(await self.service.update(m, pk, req.json(), req.q("connection"), self._actor(req)))
235
+
236
+ async def r_delete(self, req, m, pk):
237
+ await self.service.delete(m, pk, req.q("connection"), self._actor(req))
238
+ return json_response({"deleted": 1})
239
+
240
+ async def r_related(self, req, m, pk, rel):
241
+ return json_response(await self.service.related(m, pk, rel, conn=req.q("connection"), **self._page(req)))
242
+
243
+ async def r_m2m_add(self, req, m, pk, rel):
244
+ return json_response(await self.service.m2m(m, pk, rel, req.json()["ids"], True,
245
+ req.q("connection"), self._actor(req)))
246
+
247
+ async def r_m2m_remove(self, req, m, pk, rel):
248
+ return json_response(await self.service.m2m(m, pk, rel, req.json()["ids"], False,
249
+ req.q("connection"), self._actor(req)))
@@ -0,0 +1,55 @@
1
+ """Framework-agnostic request/response objects. Every adapter speaks only these."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, List, Optional
7
+
8
+
9
+ @dataclass
10
+ class StudioRequest:
11
+ method: str # "GET", "POST", "PATCH", "DELETE"
12
+ path: str # relative to the mount point, starts with "/"
13
+ query: Dict[str, List[str]] = field(default_factory=dict)
14
+ headers: Dict[str, str] = field(default_factory=dict) # lower-case keys
15
+ body: bytes = b""
16
+ client: Optional[str] = None # remote IP, if the framework knows it
17
+ state: Dict[str, Any] = field(default_factory=dict) # auth hooks may store e.g. {"user": ...}
18
+ raw: Any = None # the framework's native request/scope
19
+
20
+ def q(self, key: str, default: Optional[str] = None) -> Optional[str]:
21
+ values = self.query.get(key)
22
+ return values[0] if values else default
23
+
24
+ def json(self) -> Any:
25
+ return json.loads(self.body.decode("utf-8") or "{}")
26
+
27
+
28
+ @dataclass
29
+ class StudioResponse:
30
+ status: int = 200
31
+ headers: Dict[str, str] = field(default_factory=dict)
32
+ body: bytes = b""
33
+
34
+
35
+ class StudioError(Exception):
36
+ def __init__(self, status: int, code: str, message: str, headers: Optional[Dict[str, str]] = None,
37
+ detail: Optional[Dict[str, Any]] = None):
38
+ super().__init__(message)
39
+ self.status, self.code, self.message = status, code, message
40
+ self.headers = headers or {}
41
+ # Structured extras (e.g. the failing batch operation index) are merged
42
+ # into the error object without changing the existing code/message keys.
43
+ self.detail = detail or {}
44
+
45
+
46
+ def json_response(data: Any, status: int = 200, headers: Optional[Dict[str, str]] = None) -> StudioResponse:
47
+ h = {"content-type": "application/json; charset=utf-8"}
48
+ h.update(headers or {})
49
+ return StudioResponse(status, h, json.dumps(data, default=str).encode("utf-8"))
50
+
51
+
52
+ def error_response(err: StudioError) -> StudioResponse:
53
+ error = {"code": err.code, "message": err.message}
54
+ error.update(err.detail)
55
+ return json_response({"error": error}, err.status, err.headers)
@@ -0,0 +1,18 @@
1
+ """Server-side locale metadata for v0.9.0.
2
+
3
+ The translations themselves ship as static JS dictionaries; this module is
4
+ only the small, typed contract used by ``Studio(locale=...)`` and ``/api/schema``
5
+ so a host can pick the initial language without editing client state.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ DEFAULT_LOCALE = "en"
10
+ LOCALES = ("en", "zh-CN")
11
+
12
+
13
+ def normalize_locale(value: str) -> str:
14
+ """Resolve a locale case-insensitively, or fall back to English."""
15
+ for candidate in LOCALES:
16
+ if candidate.lower() == str(value).strip().lower().replace("_", "-"):
17
+ return candidate
18
+ return DEFAULT_LOCALE