flask-deck 0.3.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 (57) hide show
  1. flask_deck/__init__.py +184 -0
  2. flask_deck/adapters/__init__.py +23 -0
  3. flask_deck/adapters/sqlalchemy.py +272 -0
  4. flask_deck/audit.py +363 -0
  5. flask_deck/auth.py +462 -0
  6. flask_deck/branding.py +217 -0
  7. flask_deck/charts.py +514 -0
  8. flask_deck/cli.py +135 -0
  9. flask_deck/config.py +81 -0
  10. flask_deck/dashboard.py +416 -0
  11. flask_deck/deck.py +4153 -0
  12. flask_deck/demo.py +1066 -0
  13. flask_deck/events.py +309 -0
  14. flask_deck/exceptions.py +34 -0
  15. flask_deck/exporter.py +240 -0
  16. flask_deck/formatters.py +386 -0
  17. flask_deck/i18n.py +399 -0
  18. flask_deck/icons.py +92 -0
  19. flask_deck/importer.py +612 -0
  20. flask_deck/introspection.py +376 -0
  21. flask_deck/jobs.py +382 -0
  22. flask_deck/mfa.py +670 -0
  23. flask_deck/model_view.py +1097 -0
  24. flask_deck/py.typed +0 -0
  25. flask_deck/query.py +1220 -0
  26. flask_deck/schema_graph.py +137 -0
  27. flask_deck/security.py +373 -0
  28. flask_deck/sql_console.py +391 -0
  29. flask_deck/sso.py +293 -0
  30. flask_deck/static/css/deck.css +1333 -0
  31. flask_deck/static/js/deck.js +1433 -0
  32. flask_deck/storage.py +669 -0
  33. flask_deck/templates/flask_deck/audit_list.html +117 -0
  34. flask_deck/templates/flask_deck/base.html +454 -0
  35. flask_deck/templates/flask_deck/custom_page.html +12 -0
  36. flask_deck/templates/flask_deck/dashboard.html +32 -0
  37. flask_deck/templates/flask_deck/diagnostics.html +80 -0
  38. flask_deck/templates/flask_deck/error.html +15 -0
  39. flask_deck/templates/flask_deck/import_wizard.html +143 -0
  40. flask_deck/templates/flask_deck/jobs_list.html +95 -0
  41. flask_deck/templates/flask_deck/login.html +93 -0
  42. flask_deck/templates/flask_deck/login_mfa.html +59 -0
  43. flask_deck/templates/flask_deck/mfa_setup.html +121 -0
  44. flask_deck/templates/flask_deck/model_detail.html +124 -0
  45. flask_deck/templates/flask_deck/model_form.html +389 -0
  46. flask_deck/templates/flask_deck/model_list.html +489 -0
  47. flask_deck/templates/flask_deck/partials/drawer_detail.html +93 -0
  48. flask_deck/templates/flask_deck/partials/widget_grid.html +207 -0
  49. flask_deck/templates/flask_deck/rbac_matrix.html +59 -0
  50. flask_deck/templates/flask_deck/record_history.html +102 -0
  51. flask_deck/templates/flask_deck/schema_inspector.html +83 -0
  52. flask_deck/templates/flask_deck/sql_console.html +87 -0
  53. flask_deck-0.3.0.dist-info/METADATA +382 -0
  54. flask_deck-0.3.0.dist-info/RECORD +57 -0
  55. flask_deck-0.3.0.dist-info/WHEEL +4 -0
  56. flask_deck-0.3.0.dist-info/entry_points.txt +5 -0
  57. flask_deck-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,376 @@
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ import re
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass
7
+ from typing import Any, Literal
8
+
9
+ import sqlalchemy as sa
10
+ from sqlalchemy.orm import Mapper, RelationshipProperty
11
+
12
+ from flask_deck.security import is_sensitive_field
13
+
14
+ FieldType = Literal[
15
+ "string",
16
+ "text",
17
+ "integer",
18
+ "float",
19
+ "decimal",
20
+ "boolean",
21
+ "date",
22
+ "datetime",
23
+ "time",
24
+ "enum",
25
+ "json",
26
+ "array",
27
+ "uuid",
28
+ "binary",
29
+ "email",
30
+ "url",
31
+ "password",
32
+ ]
33
+
34
+ RelationshipDirection = Literal["MANYTOONE", "ONETOMANY", "MANYTOMANY"]
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class FieldMeta:
39
+ """Immutable metadata describing one SQLAlchemy column."""
40
+
41
+ name: str
42
+ label: str
43
+ field_type: FieldType
44
+ python_type: type[Any] | None
45
+ nullable: bool
46
+ primary_key: bool
47
+ unique: bool
48
+ indexed: bool
49
+ autoincrement: bool
50
+ has_default: bool
51
+ max_length: int | None
52
+ choices: tuple[tuple[str, str], ...]
53
+ enum_class: type[enum.Enum] | None
54
+ is_sensitive: bool
55
+ is_heavy: bool
56
+ fk_column: str | None
57
+ fk_target_table: str | None
58
+ fk_target_model: type[Any] | None
59
+ fk_relationship_name: str | None
60
+ array_item_type: FieldType | None = None
61
+ is_jsonb: bool = False
62
+
63
+
64
+ @dataclass(frozen=True, slots=True)
65
+ class RelationshipMeta:
66
+ """Immutable metadata describing one SQLAlchemy ORM relationship."""
67
+
68
+ name: str
69
+ label: str
70
+ direction: RelationshipDirection
71
+ target_model: type[Any]
72
+ uselist: bool
73
+ local_columns: tuple[str, ...]
74
+ remote_columns: tuple[str, ...]
75
+ back_populates: str | None
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class ModelMeta:
80
+ """Frozen, cached schema representation of a SQLAlchemy 2.0 model."""
81
+
82
+ model: type[Any]
83
+ name: str
84
+ label: str
85
+ plural_label: str
86
+ slug: str
87
+ table_name: str
88
+ primary_keys: tuple[FieldMeta, ...]
89
+ fields: tuple[FieldMeta, ...]
90
+ fields_by_name: dict[str, FieldMeta]
91
+ relationships: tuple[RelationshipMeta, ...]
92
+ relationships_by_name: dict[str, RelationshipMeta]
93
+ fk_column_to_rel: dict[str, RelationshipMeta]
94
+ sensitive_fields: frozenset[str]
95
+ heavy_fields: frozenset[str]
96
+ indexed_fields: frozenset[str]
97
+ schema: str | None = None
98
+
99
+
100
+ _CAMEL_RE_1 = re.compile(r"(.)([A-Z][a-z]+)")
101
+ _CAMEL_RE_2 = re.compile(r"([a-z0-9])([A-Z])")
102
+
103
+
104
+ def _to_snake(name: str) -> str:
105
+ s1 = _CAMEL_RE_1.sub(r"\1_\2", name)
106
+ return _CAMEL_RE_2.sub(r"\1_\2", s1).lower()
107
+
108
+
109
+ def humanize(name: str) -> str:
110
+ """Convert snake_case or CamelCase identifier into Title Case."""
111
+ snake = _to_snake(name)
112
+ cleaned = snake.replace("_id", "") if snake.endswith("_id") and len(snake) > 3 else snake
113
+ return " ".join(part.capitalize() for part in cleaned.split("_") if part)
114
+
115
+
116
+ def pluralize(word: str) -> str:
117
+ """Minimal deterministic English pluralizer for model display labels."""
118
+ if not word:
119
+ return word
120
+ lower = word.lower()
121
+ if lower.endswith(("s", "x", "z", "ch", "sh")):
122
+ return f"{word}es"
123
+ if lower.endswith("y") and len(word) > 1 and lower[-2] not in "aeiou":
124
+ return f"{word[:-1]}ies"
125
+ return f"{word}s"
126
+
127
+
128
+ def slugify(name: str) -> str:
129
+ """Build URL-safe kebab-case slug from model class name."""
130
+ snake = _to_snake(name)
131
+ return pluralize(snake).replace("_", "-")
132
+
133
+
134
+ def _classify_column(
135
+ col: sa.Column[Any],
136
+ is_sensitive: bool,
137
+ ) -> tuple[FieldType, tuple[tuple[str, str], ...], type[enum.Enum] | None, int | None, bool]:
138
+ col_type = col.type
139
+ choices: tuple[tuple[str, str], ...] = ()
140
+ enum_cls: type[enum.Enum] | None = None
141
+ max_length: int | None = getattr(col_type, "length", None)
142
+ is_heavy = False
143
+
144
+ if isinstance(col_type, sa.Enum):
145
+ if col_type.enum_class is not None and issubclass(col_type.enum_class, enum.Enum):
146
+ enum_cls = col_type.enum_class
147
+ choices = tuple((str(m.value), humanize(m.name)) for m in enum_cls)
148
+ else:
149
+ choices = tuple((str(v), humanize(str(v))) for v in (col_type.enums or ()))
150
+ return "enum", choices, enum_cls, max_length, False
151
+
152
+ if isinstance(col_type, sa.Boolean):
153
+ return "boolean", (), None, None, False
154
+ if isinstance(col_type, sa.DateTime):
155
+ return "datetime", (), None, None, False
156
+ if isinstance(col_type, sa.Date):
157
+ return "date", (), None, None, False
158
+ if isinstance(col_type, sa.Time):
159
+ return "time", (), None, None, False
160
+ if isinstance(col_type, sa.Numeric) and not isinstance(col_type, sa.Float):
161
+ return "decimal", (), None, None, False
162
+ if isinstance(col_type, sa.Float):
163
+ return "float", (), None, None, False
164
+ if isinstance(col_type, sa.Integer):
165
+ return "integer", (), None, None, False
166
+ if isinstance(col_type, sa.ARRAY):
167
+ return "array", (), None, None, False
168
+ if isinstance(col_type, sa.JSON):
169
+ return "json", (), None, None, True
170
+ if isinstance(col_type, sa.Uuid):
171
+ return "uuid", (), None, 36, False
172
+ if isinstance(col_type, sa.LargeBinary):
173
+ return "binary", (), None, None, True
174
+ if isinstance(col_type, sa.Text):
175
+ return "text", (), None, max_length, True
176
+
177
+ # String-like column heuristics
178
+ name_lower = col.name.lower()
179
+ if is_sensitive:
180
+ return "password", (), None, max_length, False
181
+ if "email" in name_lower:
182
+ return "email", (), None, max_length, False
183
+ if name_lower in {"url", "website", "homepage", "avatar_url", "image_url"} or name_lower.endswith(
184
+ "_url"
185
+ ):
186
+ return "url", (), None, max_length, False
187
+ if max_length is not None and max_length >= 500:
188
+ is_heavy = True
189
+
190
+ return "string", (), None, max_length, is_heavy
191
+
192
+
193
+ def _collect_indexed_columns(table: sa.Table) -> frozenset[str]:
194
+ indexed: set[str] = set()
195
+ for col in table.columns:
196
+ if col.primary_key or col.index or col.unique:
197
+ indexed.add(col.name)
198
+ for idx in table.indexes:
199
+ cols = list(idx.columns)
200
+ if cols:
201
+ # Leading column of a composite index can serve equality/prefix lookups.
202
+ indexed.add(cols[0].name)
203
+ for constraint in table.constraints:
204
+ if isinstance(constraint, sa.UniqueConstraint):
205
+ cols = list(constraint.columns)
206
+ if cols:
207
+ indexed.add(cols[0].name)
208
+ return frozenset(indexed)
209
+
210
+
211
+ def introspect_model(
212
+ model: type[Any],
213
+ *,
214
+ extra_sensitive_patterns: Iterable[re.Pattern[str]] = (),
215
+ slug_override: str | None = None,
216
+ ) -> ModelMeta:
217
+ """Inspect a SQLAlchemy 2.0 mapped model once and produce frozen ModelMeta."""
218
+ mapper: Mapper[Any] = sa.inspect(model)
219
+ table = mapper.local_table
220
+ if not isinstance(table, sa.Table):
221
+ raise TypeError(f"Model {model.__name__} must be mapped to a concrete SQLAlchemy Table")
222
+
223
+ # Build table fullname -> model class lookup from registry for FK target resolution.
224
+ table_to_model: dict[str, type[Any]] = {}
225
+ for other_mapper in mapper.registry.mappers:
226
+ other_table = other_mapper.local_table
227
+ if isinstance(other_table, sa.Table):
228
+ table_to_model[other_table.fullname] = other_mapper.class_
229
+ table_to_model.setdefault(other_table.name, other_mapper.class_)
230
+
231
+ # Map SQL column name -> ORM attribute key so aliased columns map cleanly.
232
+ col_name_to_attr: dict[str, str] = {}
233
+ for attr in mapper.column_attrs:
234
+ c0 = attr.columns[0]
235
+ if isinstance(c0, sa.Column):
236
+ col_name_to_attr[c0.name] = attr.key
237
+
238
+ # Relationships first so FK columns can link directly to their MANYTOONE relationship.
239
+ relationships: list[RelationshipMeta] = []
240
+ fk_column_to_rel: dict[str, RelationshipMeta] = {}
241
+
242
+ for rel in mapper.relationships:
243
+ if not isinstance(rel, RelationshipProperty):
244
+ continue
245
+ direction_name = rel.direction.name
246
+ if direction_name not in {"MANYTOONE", "ONETOMANY", "MANYTOMANY"}:
247
+ continue
248
+ direction: RelationshipDirection = direction_name # type: ignore[assignment]
249
+ local_cols = tuple(col_name_to_attr.get(c.name, c.name) for c in rel.local_columns)
250
+ remote_cols = tuple(c.name for c in rel.remote_side)
251
+ rel_meta = RelationshipMeta(
252
+ name=rel.key,
253
+ label=humanize(rel.key),
254
+ direction=direction,
255
+ target_model=rel.mapper.class_,
256
+ uselist=bool(rel.uselist),
257
+ local_columns=local_cols,
258
+ remote_columns=remote_cols,
259
+ back_populates=rel.back_populates,
260
+ )
261
+ relationships.append(rel_meta)
262
+ if direction == "MANYTOONE" and len(local_cols) == 1:
263
+ fk_column_to_rel[local_cols[0]] = rel_meta
264
+
265
+ raw_indexed_cols = _collect_indexed_columns(table)
266
+ indexed_cols = frozenset(col_name_to_attr.get(c, c) for c in raw_indexed_cols)
267
+ fields: list[FieldMeta] = []
268
+ primary_keys: list[FieldMeta] = []
269
+ sensitive_set: set[str] = set()
270
+ heavy_set: set[str] = set()
271
+
272
+ for attr in mapper.column_attrs:
273
+ col = attr.columns[0]
274
+ if not isinstance(col, sa.Column):
275
+ continue
276
+ col_name = attr.key
277
+ sensitive = is_sensitive_field(col_name, extra_sensitive_patterns)
278
+ field_type, choices, enum_cls, max_length, is_heavy = _classify_column(col, sensitive)
279
+ if sensitive:
280
+ sensitive_set.add(col_name)
281
+ if is_heavy:
282
+ heavy_set.add(col_name)
283
+
284
+ try:
285
+ py_type: type[Any] | None = col.type.python_type
286
+ except NotImplementedError:
287
+ py_type = None
288
+
289
+ fk_target_table: str | None = None
290
+ fk_target_model: type[Any] | None = None
291
+ fk_col_str: str | None = None
292
+ fk_rel_name: str | None = None
293
+ if col.foreign_keys:
294
+ fk = next(iter(col.foreign_keys))
295
+ fk_target_table = fk.column.table.name
296
+ fk_target_fullname = fk.column.table.fullname
297
+ fk_col_str = f"{fk_target_table}.{fk.column.name}"
298
+ fk_target_model = table_to_model.get(fk_target_fullname) or table_to_model.get(
299
+ fk_target_table
300
+ )
301
+ rel_match = fk_column_to_rel.get(col_name) or fk_column_to_rel.get(col.name)
302
+ if rel_match is not None:
303
+ fk_rel_name = rel_match.name
304
+ fk_target_model = rel_match.target_model
305
+
306
+ has_default = col.default is not None or col.server_default is not None
307
+ autoincrement = bool(
308
+ col.primary_key
309
+ and field_type == "integer"
310
+ and col.autoincrement in (True, "auto")
311
+ and not col.foreign_keys
312
+ )
313
+
314
+ array_item_type: FieldType | None = None
315
+ if isinstance(col.type, sa.ARRAY):
316
+ item_t = col.type.item_type
317
+ if isinstance(item_t, sa.Integer):
318
+ array_item_type = "integer"
319
+ elif isinstance(item_t, sa.Float):
320
+ array_item_type = "float"
321
+ elif isinstance(item_t, sa.Boolean):
322
+ array_item_type = "boolean"
323
+ else:
324
+ array_item_type = "string"
325
+ is_jsonb = col.type.__class__.__name__.upper() == "JSONB"
326
+
327
+ fmeta = FieldMeta(
328
+ name=col_name,
329
+ label=humanize(col_name),
330
+ field_type=field_type,
331
+ python_type=py_type,
332
+ nullable=bool(col.nullable),
333
+ primary_key=bool(col.primary_key),
334
+ unique=bool(col.unique),
335
+ indexed=col_name in indexed_cols,
336
+ autoincrement=autoincrement,
337
+ has_default=has_default,
338
+ max_length=max_length,
339
+ choices=choices,
340
+ enum_class=enum_cls,
341
+ is_sensitive=sensitive,
342
+ is_heavy=is_heavy,
343
+ fk_column=fk_col_str,
344
+ fk_target_table=fk_target_table,
345
+ fk_target_model=fk_target_model,
346
+ fk_relationship_name=fk_rel_name,
347
+ array_item_type=array_item_type,
348
+ is_jsonb=is_jsonb,
349
+ )
350
+ fields.append(fmeta)
351
+ if fmeta.primary_key:
352
+ primary_keys.append(fmeta)
353
+
354
+ if not primary_keys:
355
+ raise ValueError(f"Model {model.__name__} must declare at least one primary key column")
356
+
357
+ class_name = model.__name__
358
+ label = humanize(class_name)
359
+ return ModelMeta(
360
+ model=model,
361
+ name=class_name,
362
+ label=label,
363
+ plural_label=pluralize(label),
364
+ slug=slug_override or slugify(class_name),
365
+ table_name=table.name,
366
+ primary_keys=tuple(primary_keys),
367
+ fields=tuple(fields),
368
+ fields_by_name={f.name: f for f in fields},
369
+ relationships=tuple(relationships),
370
+ relationships_by_name={r.name: r for r in relationships},
371
+ fk_column_to_rel=fk_column_to_rel,
372
+ sensitive_fields=frozenset(sensitive_set),
373
+ heavy_fields=frozenset(heavy_set),
374
+ indexed_fields=indexed_cols,
375
+ schema=table.schema,
376
+ )