forked from aminalaee/sqladmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
393 lines (320 loc) · 12.2 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
from dataclasses import dataclass
from typing import (
Any,
ClassVar,
Dict,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
no_type_check,
)
import anyio
from sqlalchemy import Column, func, inspect, select
from sqlalchemy.engine.base import Engine
from sqlalchemy.exc import NoInspectionAvailable
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.orm.attributes import InstrumentedAttribute
from sqlalchemy.orm.exc import NoResultFound
from wtforms import Form
from sqladmin.exceptions import InvalidColumnError, InvalidModelError
from sqladmin.forms import get_model_form
from sqladmin.helpers import prettify_class_name, slugify_class_name
__all__ = [
"ModelAdmin",
]
@dataclass
class Pagination:
rows: List[Any]
page: int
page_size: int
count: int
next_page_url: Optional[str] = None
previous_page_url: Optional[str] = None
class ModelAdminMeta(type):
"""Metaclass used to specify class variables in ModelAdmin.
Danger:
This class should almost never be used directly.
"""
@no_type_check
def __new__(mcls, name, bases, attrs: dict, **kwargs: Any):
cls: Type["ModelAdmin"] = super().__new__(mcls, name, bases, attrs)
model = kwargs.get("model")
if not model:
return cls
try:
mapper = inspect(model)
except NoInspectionAvailable:
raise InvalidModelError(
f"Class {model.__name__} is not a SQLAlchemy model."
)
assert len(mapper.primary_key) == 1, "Multiple PK columns not supported."
cls.pk_column = mapper.primary_key[0]
cls.identity = slugify_class_name(model.__name__)
cls.model = model
cls.name = attrs.get("name", prettify_class_name(cls.model.__name__))
cls.name_plural = attrs.get("name_plural", f"{cls.name}s")
cls.icon = attrs.get("icon")
mcls._check_conflicting_options(["column_list", "column_exclude_list"], attrs)
mcls._check_conflicting_options(
["column_details_list", "column_details_exclude_list"], attrs
)
return cls
@classmethod
def _check_conflicting_options(cls, keys: List[str], attrs: dict) -> None:
if all(k in attrs for k in keys):
raise AssertionError(f"Cannot use {' and '.join(keys)} together.")
@classmethod
def _get_sessionmaker(mcls, engine: Union[Engine, AsyncEngine]) -> None:
if isinstance(engine, Engine):
return sessionmaker(bind=engine, class_=Session)
else:
return sessionmaker(bind=engine, class_=AsyncSession)
class ModelAdmin(metaclass=ModelAdminMeta):
"""Base class for defining admnistrative behaviour for the model.
???+ usage
```python
from sqladmin import ModelAdmin
from mymodels import User # SQLAlchemy model
class UserAdmin(ModelAdmin, model=User):
can_create = True
```
"""
model: ClassVar[type]
engine: ClassVar[Union[Engine, AsyncEngine]]
sessionmaker: ClassVar[sessionmaker]
# Internals
pk_column: ClassVar[Column]
identity: ClassVar[str]
# Metadata
name: ClassVar[str] = ""
"""Name of ModelAdmin to display.
Default value is set to Model class name.
"""
name_plural: ClassVar[str] = ""
"""Plural name of ModelAdmin.
Default value is Model class name + `s`.
"""
icon: ClassVar[str] = ""
"""Display icon for ModelAdmin in the sidebar.
Currently only supports FontAwesome icons.
???+ example
```python
class UserAdmin(ModelAdmin, model=User):
icon = "fas fa-user"
```
"""
# Permissions
can_create: ClassVar[bool] = True
"""Permission for creating new Models. Default value is set to `True`."""
can_edit: ClassVar[bool] = True
"""Permission for editing Models. Default value is set to `True`."""
can_delete: ClassVar[bool] = True
"""Permission for deleting Models. Default value is set to `True`."""
can_view_details: ClassVar[bool] = True
"""Permission for viewing full details of Models.
Default value is set to `True`.
"""
# List page
column_list: ClassVar[Sequence[Union[str, InstrumentedAttribute]]] = []
"""List of columns to display in `List` page.
Columns can either be string names or SQLAlchemy columns.
???+ note
By default only Model primary key is displayed.
???+ example
```python
class UserAdmin(ModelAdmin, model=User):
column_list = [User.id, User.name]
```
"""
column_exclude_list: ClassVar[Sequence[Union[str, InstrumentedAttribute]]] = []
"""List of columns to exclude in `List` page.
Columns can either be string names or SQLAlchemy columns.
???+ example
```python
class UserAdmin(ModelAdmin, model=User):
column_exclude_list = [User.id, User.name]
```
"""
page_size: ClassVar[int] = 10
"""Default number of items to display in `List` page pagination.
Default value is set to `10`.
???+ example
```python
class UserAdmin(ModelAdmin, model=User):
page_size = 25
```
"""
page_size_options: ClassVar[Sequence[int]] = [10, 25, 50, 100]
"""Pagination choices displayed in `List` page.
Default value is set to `[10, 25, 50, 100]`.
???+ example
```python
class UserAdmin(ModelAdmin, model=User):
page_size_options = [50, 100]
```
"""
# Details page
column_details_list: ClassVar[Sequence[Union[str, InstrumentedAttribute]]] = []
"""List of columns to display in `Detail` page.
Columns can either be string names or SQLAlchemy columns.
???+ note
By default all columns of Model are displayed.
???+ example
```python
class UserAdmin(ModelAdmin, model=User):
column_details_list = [User.id, User.name, User.mail]
```
"""
column_details_exclude_list: ClassVar[
Sequence[Union[str, InstrumentedAttribute]]
] = []
"""List of columns to exclude from displaying in `Detail` page.
Columns can either be string names or SQLAlchemy columns.
???+ example
```python
class UserAdmin(ModelAdmin, model=User):
column_details_exclude_list = [User.mail]
```
"""
column_labels: ClassVar[Dict[Union[str, InstrumentedAttribute], str]] = {}
"""A mapping of column labels, used to map column names to new names.
Dictionary keys can be string names or SQLAlchemy columns with string values.
???+ example
```python
class UserAdmin(ModelAdmin, model=User):
column_labels = {User.mail: "Email"}
```
"""
@classmethod
async def count(cls) -> int:
query = select(func.count(cls.pk_column))
if isinstance(cls.engine, Engine):
with cls.sessionmaker() as session:
result = await anyio.to_thread.run_sync(session.execute, query)
return result.scalar_one()
else:
async with cls.sessionmaker() as session:
result = await session.execute(query)
return result.scalar_one()
@classmethod
async def list(cls, page: int, page_size: int) -> Pagination:
page_size = min(page_size or cls.page_size, max(cls.page_size_options))
count = await cls.count()
query = (
select(cls.model)
.order_by(cls.pk_column)
.limit(page_size)
.offset((page - 1) * page_size)
)
pagination = Pagination(
rows=[],
page=page,
page_size=page_size,
count=count,
)
if isinstance(cls.engine, Engine):
with cls.sessionmaker() as session:
items = await anyio.to_thread.run_sync(session.execute, query)
pagination.rows = items.scalars().all()
return pagination
else:
async with cls.sessionmaker() as session:
items = await session.execute(query)
pagination.rows = items.scalars().all()
return pagination
@classmethod
async def get_model_by_pk(cls, value: Any) -> Any:
query = select(cls.model).where(cls.pk_column == value)
if isinstance(cls.engine, Engine):
with cls.sessionmaker() as session:
result = await anyio.to_thread.run_sync(session.execute, query)
try:
return result.scalar_one()
except NoResultFound:
return None
else:
async with cls.sessionmaker() as session:
result = await session.execute(query)
try:
return result.scalar_one()
except NoResultFound:
return None
@classmethod
def get_column_value(cls, obj: type, column: Column) -> Any:
return getattr(obj, column.name, None)
@classmethod
def get_column_by_attr(cls, attr: Union[str, InstrumentedAttribute]) -> Column:
try:
mapper = inspect(cls.model)
if isinstance(attr, str):
return mapper.columns[attr]
else:
return mapper.columns[attr.name]
except KeyError:
raise InvalidColumnError(
f"Model '{cls.model.__name__}' has no attribute '{attr}'."
)
@classmethod
def get_model_columns(cls) -> List[Column]:
return list(inspect(cls.model).columns)
@classmethod
def get_list_columns(cls) -> List[Tuple[str, Column]]:
"""Get list of columns to display in List page."""
column_list = getattr(cls, "column_list", None)
column_exclude_list = getattr(cls, "column_exclude_list", None)
if column_list:
columns = [cls.get_column_by_attr(attr) for attr in cls.column_list]
elif column_exclude_list:
exclude_columns = [
cls.get_column_by_attr(attr) for attr in column_exclude_list
]
all_columns = cls.get_model_columns()
columns = list(set(all_columns) - set(exclude_columns))
else:
columns = [cls.pk_column]
return [(cls.get_column_labels().get(c, c.name), c) for c in columns]
@classmethod
def get_details_columns(cls) -> List[Tuple[str, Column]]:
"""Get list of columns to display in Detail page."""
column_details_list = getattr(cls, "column_details_list", None)
column_details_exclude_list = getattr(cls, "column_details_exclude_list", None)
if column_details_list:
columns = [cls.get_column_by_attr(attr) for attr in column_details_list]
elif column_details_exclude_list:
exclude_columns = [
cls.get_column_by_attr(attr) for attr in column_details_exclude_list
]
all_columns = cls.get_model_columns()
columns = list(set(all_columns) - set(exclude_columns))
else:
columns = cls.get_model_columns()
return [(cls.get_column_labels().get(c, c.name), c) for c in columns]
@classmethod
def get_column_labels(cls) -> Dict[Column, str]:
return {
cls.get_column_by_attr(column_label): value
for column_label, value in cls.column_labels.items()
}
@classmethod
async def delete_model(cls, obj: type) -> None:
if isinstance(cls.engine, Engine):
with cls.sessionmaker.begin() as session:
await anyio.to_thread.run_sync(session.delete, obj)
else:
async with cls.sessionmaker.begin() as session:
await session.delete(obj)
@classmethod
async def insert_model(cls, obj: type) -> Any:
if isinstance(cls.engine, Engine):
with cls.sessionmaker.begin() as session:
await anyio.to_thread.run_sync(session.add, obj)
else:
async with cls.sessionmaker.begin() as session:
session.add(obj)
@classmethod
async def scaffold_form(cls) -> Type[Form]:
return await get_model_form(model=cls.model, engine=cls.engine)