devadmin 0.1.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 (73) hide show
  1. devadmin/__init__.py +19 -0
  2. devadmin/__main__.py +5 -0
  3. devadmin/adapters/__init__.py +0 -0
  4. devadmin/adapters/base.py +175 -0
  5. devadmin/adapters/tortoise/__init__.py +81 -0
  6. devadmin/adapters/tortoise/introspect.py +209 -0
  7. devadmin/adapters/tortoise/models.py +34 -0
  8. devadmin/adapters/tortoise/queries.py +330 -0
  9. devadmin/adapters/tortoise/related.py +215 -0
  10. devadmin/adapters/tortoise/store.py +156 -0
  11. devadmin/auth/__init__.py +16 -0
  12. devadmin/auth/csrf.py +18 -0
  13. devadmin/auth/ip.py +28 -0
  14. devadmin/auth/login.py +149 -0
  15. devadmin/auth/session.py +94 -0
  16. devadmin/cli.py +314 -0
  17. devadmin/config.py +34 -0
  18. devadmin/core/__init__.py +0 -0
  19. devadmin/core/binding.py +609 -0
  20. devadmin/core/forms.py +475 -0
  21. devadmin/core/listing.py +400 -0
  22. devadmin/core/options.py +99 -0
  23. devadmin/core/paths.py +39 -0
  24. devadmin/core/site.py +288 -0
  25. devadmin/core/values.py +122 -0
  26. devadmin/history/__init__.py +38 -0
  27. devadmin/history/diff.py +109 -0
  28. devadmin/history/encoding.py +120 -0
  29. devadmin/history/records.py +40 -0
  30. devadmin/history/render.py +129 -0
  31. devadmin/history/service.py +256 -0
  32. devadmin/web/__init__.py +0 -0
  33. devadmin/web/app.py +106 -0
  34. devadmin/web/deps.py +275 -0
  35. devadmin/web/guard.py +178 -0
  36. devadmin/web/static/autocomplete.js +231 -0
  37. devadmin/web/static/devadmin.css +1645 -0
  38. devadmin/web/static/devadmin.js +129 -0
  39. devadmin/web/static/htmx.min.js +1 -0
  40. devadmin/web/static/icons/check.svg +1 -0
  41. devadmin/web/static/icons/clock.svg +1 -0
  42. devadmin/web/static/icons/cross.svg +1 -0
  43. devadmin/web/static/icons/down.svg +1 -0
  44. devadmin/web/static/icons/eye.svg +1 -0
  45. devadmin/web/static/icons/lock.svg +1 -0
  46. devadmin/web/static/icons/pencil.svg +1 -0
  47. devadmin/web/static/icons/plus.svg +1 -0
  48. devadmin/web/static/icons/right.svg +1 -0
  49. devadmin/web/static/icons/trash.svg +1 -0
  50. devadmin/web/static/icons/up.svg +1 -0
  51. devadmin/web/templates/_field.html +35 -0
  52. devadmin/web/templates/_history.html +19 -0
  53. devadmin/web/templates/_pagination.html +8 -0
  54. devadmin/web/templates/action_confirm.html +26 -0
  55. devadmin/web/templates/base.html +63 -0
  56. devadmin/web/templates/delete.html +62 -0
  57. devadmin/web/templates/error.html +9 -0
  58. devadmin/web/templates/form.html +34 -0
  59. devadmin/web/templates/history.html +59 -0
  60. devadmin/web/templates/index.html +49 -0
  61. devadmin/web/templates/list.html +88 -0
  62. devadmin/web/templates/login.html +15 -0
  63. devadmin/web/templates/recent.html +25 -0
  64. devadmin/web/views_auth.py +146 -0
  65. devadmin/web/views_delete.py +774 -0
  66. devadmin/web/views_form.py +551 -0
  67. devadmin/web/views_history.py +261 -0
  68. devadmin/web/views_list.py +246 -0
  69. devadmin-0.1.0.dist-info/METADATA +702 -0
  70. devadmin-0.1.0.dist-info/RECORD +73 -0
  71. devadmin-0.1.0.dist-info/WHEEL +4 -0
  72. devadmin-0.1.0.dist-info/entry_points.txt +3 -0
  73. devadmin-0.1.0.dist-info/licenses/LICENSE +21 -0
devadmin/core/forms.py ADDED
@@ -0,0 +1,475 @@
1
+ import json
2
+ import math
3
+ import re
4
+ import uuid
5
+ from collections.abc import Callable, Mapping
6
+ from dataclasses import dataclass
7
+ from datetime import UTC, date, datetime, time
8
+ from decimal import Decimal
9
+ from enum import Enum
10
+ from typing import Any, NamedTuple
11
+
12
+ from devadmin.adapters.base import FieldInfo, FieldType
13
+ from devadmin.core.binding import BoundAdmin
14
+ from devadmin.core.values import (
15
+ ABOVE_MAX,
16
+ BELOW_MIN,
17
+ MAX_SIGNIFICANT_DIGITS,
18
+ TOO_LARGE,
19
+ TOO_MANY_DECIMAL_PLACES,
20
+ decimal_problem,
21
+ integer_problem,
22
+ whole_number,
23
+ )
24
+
25
+ MAX_VALUE_LENGTH = 1_000_000
26
+ REQUIRED = "This field is required."
27
+ INVALID_CHOICE = "Not a valid choice."
28
+ INVALID_JSON = "Enter valid JSON."
29
+ BLANK_OPTION = ("", "---------")
30
+
31
+ _INTEGER = re.compile(r"-?[0-9]+")
32
+ _DECIMAL = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)")
33
+ _DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
34
+ _TIME = re.compile(r"[0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:\.[0-9]{1,6})?)?")
35
+ _DATETIME = re.compile(
36
+ r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:\.[0-9]{1,6})?)?(?:Z|[+-][0-9]{2}:[0-9]{2})?"
37
+ )
38
+ _STRINGS = frozenset({FieldType.STR, FieldType.TEXT})
39
+ _UNSTRIPPED = frozenset({FieldType.TEXT, FieldType.JSON})
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class FormField:
44
+ info: FieldInfo
45
+ widget: str
46
+ readonly: bool
47
+ is_new: bool = False
48
+
49
+ @property
50
+ def options(self) -> list[tuple[str, str]]:
51
+ if self.info.type is FieldType.BOOL and self.info.nullable:
52
+ return [BLANK_OPTION, ("1", "Yes"), ("0", "No")]
53
+ if self.info.type is not FieldType.ENUM:
54
+ return []
55
+ choices = [(str(value), label) for value, label in self.info.choices or []]
56
+ return [BLANK_OPTION, *choices] if self.info.nullable else choices
57
+
58
+
59
+ @dataclass
60
+ class FormResult:
61
+ data: dict[str, Any]
62
+ errors: dict[str, str]
63
+ raw: dict[str, str]
64
+
65
+ @property
66
+ def ok(self) -> bool:
67
+ return not self.errors
68
+
69
+
70
+ def _int(field: FieldInfo, text: str) -> int:
71
+ if not _INTEGER.fullmatch(text):
72
+ raise ValueError("Enter a whole number.")
73
+ value = whole_number(text)
74
+ problem = integer_problem(field, value)
75
+ if problem is None:
76
+ return value
77
+ low, high = field.min_value, field.max_value
78
+ if low is not None and high is not None:
79
+ raise ValueError(f"Enter a whole number between {low} and {high}.")
80
+ if problem == BELOW_MIN and low is not None:
81
+ raise ValueError(f"Enter a whole number of at least {low}.")
82
+ if problem == ABOVE_MAX and high is not None:
83
+ raise ValueError(f"Enter a whole number of at most {high}.")
84
+ raise ValueError("Enter a smaller number.")
85
+
86
+
87
+ def _decimal(field: FieldInfo, text: str) -> Decimal:
88
+ if not _DECIMAL.fullmatch(text):
89
+ raise ValueError("Enter a number.")
90
+ value = Decimal(text)
91
+ problem = decimal_problem(field, value)
92
+ if problem is None:
93
+ return value
94
+ low, high = field.min_value, field.max_value
95
+ if problem == TOO_MANY_DECIMAL_PLACES:
96
+ raise ValueError(f"At most {field.decimal_places} decimal places.")
97
+ outside = (low is not None and value < low) or (high is not None and value > high)
98
+ if low is not None and high is not None and (problem != TOO_LARGE or outside):
99
+ raise ValueError(f"Enter a number between {low} and {high}.")
100
+ if problem == BELOW_MIN:
101
+ raise ValueError(f"Enter a number of at least {low}.")
102
+ if problem == ABOVE_MAX:
103
+ raise ValueError(f"Enter a number of at most {high}.")
104
+ raise ValueError(f"Enter a number with at most {MAX_SIGNIFICANT_DIGITS} digits.")
105
+
106
+
107
+ def _float(field: FieldInfo, text: str) -> float:
108
+ if not _DECIMAL.fullmatch(text):
109
+ raise ValueError("Enter a number.")
110
+ value = float(text)
111
+ if not math.isfinite(value):
112
+ raise ValueError("Enter a number.")
113
+ return value
114
+
115
+
116
+ def _valid_text(text: str) -> bool:
117
+ try:
118
+ text.encode("utf-8")
119
+ except UnicodeEncodeError:
120
+ return False
121
+ return True
122
+
123
+
124
+ def _check_text(text: str) -> str:
125
+ if "\x00" in text:
126
+ raise ValueError("Null characters are not allowed.")
127
+ if not _valid_text(text):
128
+ raise ValueError("Enter valid text.")
129
+ return text
130
+
131
+
132
+ def _str(field: FieldInfo, text: str) -> str:
133
+ _check_text(text)
134
+ if field.max_length is not None and len(text) > field.max_length:
135
+ raise ValueError(f"At most {field.max_length} characters.")
136
+ return text
137
+
138
+
139
+ def _text(field: FieldInfo, text: str) -> str:
140
+ return _check_text(text)
141
+
142
+
143
+ def _date(field: FieldInfo, text: str) -> date:
144
+ if not _DATE.fullmatch(text):
145
+ raise ValueError("Enter a valid date.")
146
+ try:
147
+ return date.fromisoformat(text)
148
+ except ValueError:
149
+ raise ValueError("Enter a valid date.") from None
150
+
151
+
152
+ def _time(field: FieldInfo, text: str) -> time:
153
+ if not _TIME.fullmatch(text):
154
+ raise ValueError("Enter a valid time.")
155
+ try:
156
+ return time.fromisoformat(text).replace(tzinfo=UTC)
157
+ except ValueError:
158
+ raise ValueError("Enter a valid time.") from None
159
+
160
+
161
+ def _datetime(field: FieldInfo, text: str) -> datetime:
162
+ if not _DATETIME.fullmatch(text):
163
+ raise ValueError("Enter a valid date and time.")
164
+ try:
165
+ value = datetime.fromisoformat(text)
166
+ if value.tzinfo is None:
167
+ return value.replace(tzinfo=UTC)
168
+ return value.astimezone(UTC)
169
+ except (ValueError, OverflowError):
170
+ raise ValueError("Enter a valid date and time.") from None
171
+
172
+
173
+ def _enum(field: FieldInfo, text: str) -> Any:
174
+ for value, _ in field.choices or []:
175
+ if str(value) == text:
176
+ return value
177
+ raise ValueError(INVALID_CHOICE)
178
+
179
+
180
+ def _reject_constant(name: str) -> Any:
181
+ raise ValueError(name)
182
+
183
+
184
+ def _finite_float(text: str) -> float:
185
+ value = float(text)
186
+ if not math.isfinite(value):
187
+ raise ValueError(text)
188
+ return value
189
+
190
+
191
+ def _json_strings_valid(value: Any) -> bool:
192
+ pending = [value]
193
+ while pending:
194
+ item = pending.pop()
195
+ if isinstance(item, str):
196
+ if "\x00" in item or not _valid_text(item):
197
+ return False
198
+ elif isinstance(item, dict):
199
+ pending.extend(item.keys())
200
+ pending.extend(item.values())
201
+ elif isinstance(item, list):
202
+ pending.extend(item)
203
+ return True
204
+
205
+
206
+ def _json(field: FieldInfo, text: str) -> Any:
207
+ try:
208
+ value = json.loads(text, parse_constant=_reject_constant, parse_float=_finite_float)
209
+ except (ValueError, RecursionError):
210
+ raise ValueError(INVALID_JSON) from None
211
+ if not _json_strings_valid(value):
212
+ raise ValueError(INVALID_JSON)
213
+ if value is None:
214
+ if field.nullable:
215
+ return None
216
+ raise ValueError(REQUIRED)
217
+ return value
218
+
219
+
220
+ def _uuid(field: FieldInfo, text: str) -> uuid.UUID:
221
+ try:
222
+ return uuid.UUID(text)
223
+ except ValueError:
224
+ raise ValueError("Enter a valid UUID.") from None
225
+
226
+
227
+ def _key(field: FieldInfo, text: str) -> str:
228
+ return _check_text(text)
229
+
230
+
231
+ def _plain(value: Any) -> str:
232
+ return str(value)
233
+
234
+
235
+ def _decimal_text(value: Decimal) -> str:
236
+ return format(value, "f")
237
+
238
+
239
+ def _float_text(value: float) -> str:
240
+ return format(Decimal(repr(value)), "f")
241
+
242
+
243
+ def _bool_text(value: Any) -> str:
244
+ return "on" if value else ""
245
+
246
+
247
+ def _iso(value: date) -> str:
248
+ return value.isoformat()
249
+
250
+
251
+ def _timespec(value: time | datetime) -> str:
252
+ return "milliseconds" if value.microsecond // 1000 else "seconds"
253
+
254
+
255
+ def _time_text(value: time) -> str:
256
+ if value.utcoffset() is not None:
257
+ value = datetime.combine(date(2000, 1, 2), value).astimezone(UTC).time()
258
+ clock = value.replace(tzinfo=None)
259
+ return clock.isoformat(timespec=_timespec(clock))
260
+
261
+
262
+ def _datetime_text(value: datetime) -> str:
263
+ if value.tzinfo is not None:
264
+ try:
265
+ value = value.astimezone(UTC)
266
+ except OverflowError:
267
+ pass
268
+ moment = value.replace(tzinfo=None)
269
+ return moment.isoformat(timespec=_timespec(moment))
270
+
271
+
272
+ def _enum_text(value: Any) -> str:
273
+ return str(value.value if isinstance(value, Enum) else value)
274
+
275
+
276
+ def _json_text(value: Any) -> str:
277
+ return json.dumps(value, ensure_ascii=False, indent=2, sort_keys=False)
278
+
279
+
280
+ class _Kind(NamedTuple):
281
+ widget: str
282
+ parse: Callable[[FieldInfo, str], Any] | None
283
+ text: Callable[[Any], str]
284
+
285
+
286
+ _KINDS: dict[FieldType, _Kind] = {
287
+ FieldType.INT: _Kind("number", _int, _plain),
288
+ FieldType.DECIMAL: _Kind("number", _decimal, _decimal_text),
289
+ FieldType.FLOAT: _Kind("number", _float, _float_text),
290
+ FieldType.STR: _Kind("text", _str, _plain),
291
+ FieldType.TEXT: _Kind("textarea", _text, _plain),
292
+ FieldType.BOOL: _Kind("checkbox", None, _bool_text),
293
+ FieldType.DATE: _Kind("date", _date, _iso),
294
+ FieldType.DATETIME: _Kind("datetime-local", _datetime, _datetime_text),
295
+ FieldType.TIME: _Kind("time", _time, _time_text),
296
+ FieldType.ENUM: _Kind("select", _enum, _enum_text),
297
+ FieldType.JSON: _Kind("json", _json, _json_text),
298
+ FieldType.UUID: _Kind("text", _uuid, _plain),
299
+ FieldType.FK: _Kind("autocomplete", _key, _plain),
300
+ FieldType.M2M: _Kind("readonly", None, _plain),
301
+ FieldType.UNSUPPORTED: _Kind("readonly", None, _plain),
302
+ }
303
+
304
+ _NULLABLE_BOOL: dict[str, bool | None] = {"": None, "1": True, "0": False}
305
+
306
+
307
+ def _widget(info: FieldInfo) -> str:
308
+ if info.type is FieldType.BOOL and info.nullable:
309
+ return "select"
310
+ return _KINDS[info.type].widget
311
+
312
+
313
+ def _parse_bool(field: FieldInfo, raw: str | None) -> bool | None:
314
+ if not field.nullable:
315
+ return raw is not None and raw != ""
316
+ text = (raw or "").strip()
317
+ if text not in _NULLABLE_BOOL:
318
+ raise ValueError(INVALID_CHOICE)
319
+ return _NULLABLE_BOOL[text]
320
+
321
+
322
+ def _blank(field: FieldInfo, raw: str | None) -> bool:
323
+ if raw is None:
324
+ return True
325
+ if field.type is FieldType.TEXT:
326
+ return raw == ""
327
+ return raw.strip() == ""
328
+
329
+
330
+ def parse_field(field: FieldInfo, raw: str | None) -> Any:
331
+ if raw is not None and len(raw) > MAX_VALUE_LENGTH:
332
+ raise ValueError("Value is too long.")
333
+ if field.type is FieldType.BOOL:
334
+ return _parse_bool(field, raw)
335
+ parse = _KINDS[field.type].parse
336
+ if parse is None:
337
+ raise ValueError("This field cannot be edited.")
338
+ if _blank(field, raw):
339
+ if field.nullable:
340
+ return None
341
+ if field.type in _STRINGS:
342
+ return ""
343
+ raise ValueError(REQUIRED)
344
+ if field.type is FieldType.TEXT:
345
+ text = raw.replace("\r\n", "\n")
346
+ elif field.type in _UNSTRIPPED:
347
+ text = raw
348
+ else:
349
+ text = raw.strip()
350
+ return parse(field, text)
351
+
352
+
353
+ def form_fields(admin: BoundAdmin, sensitive: set[str], *, is_new: bool, view_only: bool) -> list[FormField]:
354
+ by_name = {info.name: info for info in admin.fields}
355
+ hidden = set(sensitive) | admin.sensitive
356
+ result = []
357
+ for name in admin.form_fields:
358
+ info = by_name.get(name)
359
+ if info is None or name in hidden:
360
+ continue
361
+ widget = _widget(info)
362
+ readonly = (
363
+ view_only
364
+ or not info.editable
365
+ or name in admin.readonly_fields
366
+ or widget == "readonly"
367
+ or (info.pk and not is_new)
368
+ )
369
+ result.append(FormField(info=info, widget=widget, readonly=readonly, is_new=is_new))
370
+ return result
371
+
372
+
373
+ def _omitted_on_create(field: FormField, raw: str | None) -> bool:
374
+ info = field.info
375
+ if not (info.has_default and _blank(info, raw)):
376
+ return False
377
+ if info.pk:
378
+ return True
379
+ return not info.nullable and info.type not in _STRINGS and info.type is not FieldType.BOOL
380
+
381
+
382
+ def _same_value(info: FieldInfo, first: Any, second: Any) -> bool:
383
+ if info.type is FieldType.JSON:
384
+ return json.dumps(first, sort_keys=True) == json.dumps(second, sort_keys=True)
385
+ return type(first) is type(second) and first == second
386
+
387
+
388
+ def _line_endings(text: str) -> str:
389
+ return text.replace("\r\n", "\n").replace("\r", "\n")
390
+
391
+
392
+ def _unchanged(info: FieldInfo, submitted: str, initial: str) -> bool:
393
+ if _line_endings(submitted) == _line_endings(initial):
394
+ return True
395
+ try:
396
+ initial_value = parse_field(info, initial)
397
+ if info.type is not FieldType.JSON and _value_text(info, initial_value) != initial:
398
+ return False
399
+ return _same_value(info, parse_field(info, submitted), initial_value)
400
+ except ValueError:
401
+ return False
402
+
403
+
404
+ def parse_form(
405
+ fields: list[FormField], submitted: Mapping[str, str], initial: Mapping[str, str] | None = None
406
+ ) -> FormResult:
407
+ result = FormResult(data={}, errors={}, raw={})
408
+ for field in fields:
409
+ if field.readonly:
410
+ continue
411
+ info = field.info
412
+ name = info.name
413
+ raw = submitted.get(name)
414
+ if raw is not None and not isinstance(raw, str):
415
+ result.raw[name] = ""
416
+ result.errors[name] = "Enter a valid value."
417
+ continue
418
+ if field.widget == "checkbox":
419
+ result.raw[name] = "on" if raw else ""
420
+ else:
421
+ result.raw[name] = "" if raw is None else raw
422
+ if field.is_new:
423
+ if _omitted_on_create(field, raw):
424
+ continue
425
+ if info.pk and _blank(info, raw):
426
+ result.errors[name] = REQUIRED
427
+ continue
428
+ elif initial is not None and _unchanged(info, raw or "", initial.get(name, "")):
429
+ continue
430
+ try:
431
+ result.data[name] = parse_field(info, raw)
432
+ except ValueError as exc:
433
+ result.errors[name] = str(exc)
434
+ return result
435
+
436
+
437
+ def resolve_fk_values(
438
+ fields: list[FormField], result: FormResult, convert: Callable[[FieldInfo, str], Any]
439
+ ) -> None:
440
+ for field in fields:
441
+ name = field.info.name
442
+ if field.readonly or field.info.type is not FieldType.FK or result.data.get(name) is None:
443
+ continue
444
+ try:
445
+ result.data[name] = convert(field.info, result.data[name])
446
+ except ValueError:
447
+ del result.data[name]
448
+ result.errors[name] = INVALID_CHOICE
449
+
450
+
451
+ def _value_text(info: FieldInfo, value: Any) -> str:
452
+ if value is None:
453
+ return ""
454
+ if info.type is FieldType.BOOL and info.nullable:
455
+ return "1" if value else "0"
456
+ try:
457
+ return _KINDS[info.type].text(value)
458
+ except Exception:
459
+ pass
460
+ try:
461
+ return str(value)
462
+ except Exception:
463
+ return ""
464
+
465
+
466
+ def initial_values(fields: list[FormField], raw_row: dict[str, Any]) -> dict[str, str]:
467
+ values = {}
468
+ for field in fields:
469
+ info = field.info
470
+ if field.is_new and info.column not in raw_row:
471
+ value = info.default
472
+ else:
473
+ value = raw_row.get(info.column)
474
+ values[info.name] = _value_text(info, value)
475
+ return values