-
Notifications
You must be signed in to change notification settings - Fork 25
/
serializers.py
172 lines (146 loc) · 5.47 KB
/
serializers.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
from __future__ import annotations
import json
import typing as t
import uuid
from functools import lru_cache
import pydantic
from asyncpg.pgproto.pgproto import UUID
from piccolo.columns import Column
from piccolo.columns.column_types import (
JSON,
JSONB,
Array,
Decimal,
ForeignKey,
Numeric,
Secret,
Text,
Varchar,
)
from piccolo.table import Table
from piccolo.utils.encoding import load_json
class Config(pydantic.BaseConfig):
json_encoders = {uuid.UUID: lambda i: str(i), UUID: lambda i: str(i)}
arbitrary_types_allowed = True
def pydantic_json_validator(cls, value):
try:
load_json(value)
except json.JSONDecodeError:
raise ValueError("Unable to parse the JSON.")
else:
return value
@lru_cache()
def create_pydantic_model(
table: t.Type[Table],
exclude_columns: t.Tuple[Column, ...] = (),
include_default_columns: bool = False,
include_readable: bool = False,
all_optional: bool = False,
model_name: t.Optional[str] = None,
deserialize_json: bool = False,
) -> t.Type[pydantic.BaseModel]:
"""
Create a Pydantic model representing a table.
:param table:
The Piccolo ``Table`` you want to create a Pydantic serialiser model
for.
:param exclude_columns:
A tuple of ``Column`` instances that should be excluded from the
Pydantic model.
:param include_default_columns:
Whether to include columns like ``id`` in the serialiser. You will
typically include these columns in GET requests, but don't require
them in POST requests.
:param include_readable:
Whether to include 'readable' columns, which give a string
representation of a foreign key.
:param all_optional:
If True, all fields are optional. Useful for filters etc.
:param model_name:
By default, the classname of the Piccolo ``Table`` will be used, but
you can override it if you want multiple Pydantic models based off the
same Piccolo table.
:param deserialize_json:
By default, the values of any Piccolo JSON or JSONB columns are
returned as strings. By setting this parameter to True, they will be
returned as objects.
:returns:
A Pydantic model.
"""
columns: t.Dict[str, t.Any] = {}
validators: t.Dict[str, classmethod] = {}
piccolo_columns = (
table._meta.columns
if include_default_columns
else table._meta.non_default_columns
)
if not all(
isinstance(column, Column)
# Make sure that every column is tied to the current Table
and column._meta.table is table
for column in exclude_columns
):
raise ValueError(f"Exclude columns ({exclude_columns!r}) are invalid.")
for column in piccolo_columns:
# normal __contains__ checks __eq__ as well which returns ``Where``
# instance which always evaluates to ``True``
if any(column is obj for obj in exclude_columns):
continue
column_name = column._meta.name
is_optional = True if all_optional else not column._meta.required
#######################################################################
# Work out the column type
if isinstance(column, (Decimal, Numeric)):
value_type: t.Type = pydantic.condecimal(
max_digits=column.precision, decimal_places=column.scale
)
elif isinstance(column, Varchar):
value_type = pydantic.constr(max_length=column.length)
elif isinstance(column, Array):
value_type = t.List[column.base_column.value_type] # type: ignore
elif isinstance(column, (JSON, JSONB)):
if deserialize_json:
value_type = pydantic.Json
else:
value_type = column.value_type
validators[f"{column_name}_is_json"] = pydantic.validator(
column_name, allow_reuse=True
)(pydantic_json_validator)
else:
value_type = column.value_type
_type = t.Optional[value_type] if is_optional else value_type
#######################################################################
params: t.Dict[str, t.Any] = {
"default": None if is_optional else ...,
"nullable": column._meta.null,
}
extra = {
"help_text": column._meta.help_text,
"choices": column._meta.get_choices_dict(),
}
if isinstance(column, ForeignKey):
tablename = (
column._foreign_key_meta.resolved_references._meta.tablename
)
field = pydantic.Field(
extra={"foreign_key": True, "to": tablename, **extra},
**params,
)
if include_readable:
columns[f"{column_name}_readable"] = (str, None)
elif isinstance(column, Text):
field = pydantic.Field(format="text-area", extra=extra, **params)
elif isinstance(column, Secret):
field = pydantic.Field(extra={"secret": True, **extra})
else:
field = pydantic.Field(extra=extra, **params)
columns[column_name] = (_type, field)
model_name = model_name or table.__name__
class CustomConfig(Config):
schema_extra = {"help_text": table._meta.help_text}
return pydantic.create_model(
model_name,
__config__=CustomConfig,
__validators__=validators,
**columns,
)