/
computed_fields.rs
196 lines (179 loc) · 6.31 KB
/
computed_fields.rs
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
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList, PyString};
use pyo3::{intern, PyTraverseError, PyVisit};
use serde::ser::SerializeMap;
use serde::Serialize;
use crate::build_tools::py_schema_error_type;
use crate::definitions::DefinitionsBuilder;
use crate::py_gc::PyGcTraverse;
use crate::serializers::filter::SchemaFilter;
use crate::serializers::shared::{BuildSerializer, CombinedSerializer, PydanticSerializer, TypeSerializer};
use crate::tools::SchemaDict;
use super::errors::py_err_se_err;
use super::Extra;
#[derive(Debug, Clone)]
pub(super) struct ComputedFields(Vec<ComputedField>);
impl ComputedFields {
pub fn new(
schema: &PyDict,
config: Option<&PyDict>,
definitions: &mut DefinitionsBuilder<CombinedSerializer>,
) -> PyResult<Option<Self>> {
let py = schema.py();
if let Some(computed_fields) = schema.get_as::<&PyList>(intern!(py, "computed_fields"))? {
let computed_fields = computed_fields
.iter()
.map(|field| ComputedField::new(field, config, definitions))
.collect::<PyResult<Vec<_>>>()?;
Ok(Some(Self(computed_fields)))
} else {
Ok(None)
}
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn to_python(
&self,
model: &PyAny,
output_dict: &PyDict,
filter: &SchemaFilter<isize>,
include: Option<&PyAny>,
exclude: Option<&PyAny>,
extra: &Extra,
) -> PyResult<()> {
if extra.round_trip {
// Do not serialize computed fields
return Ok(());
}
for computed_fields in &self.0 {
computed_fields.to_python(model, output_dict, filter, include, exclude, extra)?;
}
Ok(())
}
pub fn serde_serialize<S: serde::ser::Serializer>(
&self,
model: &PyAny,
map: &mut S::SerializeMap,
filter: &SchemaFilter<isize>,
include: Option<&PyAny>,
exclude: Option<&PyAny>,
extra: &Extra,
) -> Result<(), S::Error> {
if extra.round_trip {
// Do not serialize computed fields
return Ok(());
}
for computed_field in &self.0 {
let property_name_py = computed_field.property_name_py.as_ref(model.py());
let value = model.getattr(property_name_py).map_err(py_err_se_err)?;
if extra.exclude_none && value.is_none() {
continue;
}
if let Some((next_include, next_exclude)) = filter
.key_filter(property_name_py, include, exclude)
.map_err(py_err_se_err)?
{
let cfs = ComputedFieldSerializer {
model,
computed_field,
include: next_include,
exclude: next_exclude,
extra,
};
let key = match extra.by_alias {
true => computed_field.alias.as_str(),
false => computed_field.property_name.as_str(),
};
map.serialize_entry(key, &cfs)?;
}
}
Ok(())
}
}
#[derive(Debug, Clone)]
struct ComputedField {
property_name: String,
property_name_py: Py<PyString>,
serializer: CombinedSerializer,
alias: String,
alias_py: Py<PyString>,
}
impl ComputedField {
pub fn new(
schema: &PyAny,
config: Option<&PyDict>,
definitions: &mut DefinitionsBuilder<CombinedSerializer>,
) -> PyResult<Self> {
let py = schema.py();
let schema: &PyDict = schema.downcast()?;
let property_name: &PyString = schema.get_as_req(intern!(py, "property_name"))?;
let return_schema = schema.get_as_req(intern!(py, "return_schema"))?;
let serializer = CombinedSerializer::build(return_schema, config, definitions)
.map_err(|e| py_schema_error_type!("Computed field `{}`:\n {}", property_name, e))?;
let alias_py: &PyString = schema.get_as(intern!(py, "alias"))?.unwrap_or(property_name);
Ok(Self {
property_name: property_name.extract()?,
property_name_py: property_name.into_py(py),
serializer,
alias: alias_py.extract()?,
alias_py: alias_py.into_py(py),
})
}
fn to_python(
&self,
model: &PyAny,
output_dict: &PyDict,
filter: &SchemaFilter<isize>,
include: Option<&PyAny>,
exclude: Option<&PyAny>,
extra: &Extra,
) -> PyResult<()> {
let py = model.py();
let property_name_py = self.property_name_py.as_ref(py);
if let Some((next_include, next_exclude)) = filter.key_filter(property_name_py, include, exclude)? {
let next_value = model.getattr(property_name_py)?;
let value = self
.serializer
.to_python(next_value, next_include, next_exclude, extra)?;
if extra.exclude_none && value.is_none(py) {
return Ok(());
}
let key = match extra.by_alias {
true => self.alias_py.as_ref(py),
false => property_name_py,
};
output_dict.set_item(key, value)?;
}
Ok(())
}
}
pub(crate) struct ComputedFieldSerializer<'py> {
model: &'py PyAny,
computed_field: &'py ComputedField,
include: Option<&'py PyAny>,
exclude: Option<&'py PyAny>,
extra: &'py Extra<'py>,
}
impl_py_gc_traverse!(ComputedField { serializer });
impl PyGcTraverse for ComputedFields {
fn py_gc_traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {
self.0.py_gc_traverse(visit)
}
}
impl_py_gc_traverse!(ComputedFieldSerializer<'_> { computed_field });
impl<'py> Serialize for ComputedFieldSerializer<'py> {
fn serialize<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let py = self.model.py();
let property_name_py = self.computed_field.property_name_py.as_ref(py);
let next_value = self.model.getattr(property_name_py).map_err(py_err_se_err)?;
let s = PydanticSerializer::new(
next_value,
&self.computed_field.serializer,
self.include,
self.exclude,
self.extra,
);
s.serialize(serializer)
}
}