8000 special case of datetime as not allowed in date serializer by davidhewitt · Pull Request #873 · pydantic/pydantic-core · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

8000 special case of datetime as not allowed in date serializer #873

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions src/serializers/type_serializers/datetime_etc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use pyo3::types::{PyDate, PyDateTime, PyDict, PyTime};

use crate::definitions::DefinitionsBuilder;
use crate::input::{pydate_as_date, pydatetime_as_datetime, pytime_as_time};
use crate::PydanticSerializationUnexpectedValue;

use super::{
infer_json_key, infer_serialize, infer_to_python, py_err_se_err, BuildSerializer, CombinedSerializer, Extra,
Expand All @@ -23,8 +24,20 @@ pub(crate) fn time_to_string(py_time: &PyTime) -> PyResult<String> {
pytime_as_time(py_time, None).map(|dt| dt.to_string())
}

fn downcast_date_reject_datetime(py_date: &PyAny) -> PyResult<&PyDate> {
if let Ok(py_date) = py_date.downcast::<PyDate>() {
// because `datetime` is a subclass of `date` we have to check that the value is not a
// `datetime` to avoid lossy serialization
if !py_date.is_instance_of::<PyDateTime>() {
return Ok(py_date);
}
}

Err(PydanticSerializationUnexpectedValue::new_err(None))
}

macro_rules! build_serializer {
($struct_name:ident, $expected_type:literal, $cast_as:ty, $convert_func:ident) => {
($struct_name:ident, $expected_type:literal, $downcast:path, $convert_func:ident $(, $json_check_func:ident)?) => {
#[derive(Debug, Clone)]
pub struct $struct_name;

Expand All @@ -51,7 +64,7 @@ macro_rules! build_serializer {
extra: &Extra,
) -> PyResult<PyObject> {
let py = value.py();
match value.downcast::<$cast_as>() {
match $downcast(value) {
Ok(py_value) => match extra.mode {
SerMode::Json => {
let s = $convert_func(py_value)?;
Expand All @@ -67,7 +80,7 @@ macro_rules! build_serializer {
}

fn json_key<'py>(&self, key: &'py PyAny, extra: &Extra) -> PyResult<Cow<'py, str>> {
match key.downcast::<$cast_as>() {
match $downcast(key) {
Ok(py_value) => Ok(Cow::Owned($convert_func(py_value)?)),
Err(_) => {
extra.warnings.on_fallback_py(self.get_name(), key, extra)?;
Expand All @@ -84,7 +97,7 @@ macro_rules! build_serializer {
exclude: Option<&PyAny>,
extra: &Extra,
) -> Result<S::Ok, S::Error> {
match value.downcast::<$cast_as>() {
match $downcast(value) {
Ok(py_value) => {
let s = $convert_func(py_value).map_err(py_err_se_err)?;
serializer.serialize_str(&s)
Expand All @@ -105,6 +118,11 @@ macro_rules! build_serializer {
};
}

build_serializer!(DatetimeSerializer, "datetime", PyDateTime, datetime_to_string);
build_serializer!(DateSerializer, "date", PyDate, date_to_string);
build_serializer!(TimeSerializer, "time", PyTime, time_to_string);
build_serializer!(
DatetimeSerializer,
"datetime",
PyAny::downcast::<PyDateTime>,
datetime_to_string
);
build_serializer!(DateSerializer, "date", downcast_date_reject_datetime, date_to_string);
build_serializer!(TimeSerializer, "time", PyAny::downcast::<PyTime>, time_to_string);
8 changes: 8 additions & 0 deletions tests/serializers/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,11 @@ def test_any_datetime_key():
# assert v.to_python(input_value) == v
assert v.to_python(input_value, mode='json') == {'2022-12-02T12:13:14': 1, '2022-12-02': 2, '12:13:14': 3}
assert v.to_json(input_value) == b'{"2022-12-02T12:13:14":1,"2022-12-02":2,"12:13:14":3}'


def test_date_datetime_union():
# See https://github.com/pydantic/pydantic/issues/7039#issuecomment-1671986746
v = SchemaSerializer(core_schema.union_schema([core_schema.date_schema(), core_schema.datetime_schema()]))
assert v.to_python(datetime(2022, 12, 2, 1)) == datetime(2022, 12, 2, 1)
assert v.to_python(datetime(2022, 12, 2, 1), mode='json') == '2022-12-02T01:00:00'
assert v.to_json(datetime(2022, 12, 2, 1)) == b'"2022-12-02T01:00:00"'
0