Skip to content

Commit

Permalink
Upgrade No. 8 to Pydantic v2
Browse files Browse the repository at this point in the history
  • Loading branch information
zhanymkanov committed Sep 1, 2023
1 parent b73dd9c commit 1fe5dd0
Showing 1 changed file with 13 additions and 17 deletions.
30 changes: 13 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -416,16 +416,11 @@ Having a controllable global base model allows us to customize all the models wi
For example, we could have a standard datetime format or add a super method for all subclasses of the base model.
```python
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo

import orjson
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, root_validator


def orjson_dumps(v, *, default):
# orjson.dumps returns bytes, to match standard json.dumps we need to decode
return orjson.dumps(v, default=default).decode()
from pydantic import BaseModel, ConfigDict, model_validator


def convert_datetime_to_gmt(dt: datetime) -> str:
Expand All @@ -435,15 +430,15 @@ def convert_datetime_to_gmt(dt: datetime) -> str:
return dt.strftime("%Y-%m-%dT%H:%M:%S%z")


class ORJSONModel(BaseModel):
class Config:
json_loads = orjson.loads
json_dumps = orjson_dumps
json_encoders = {datetime: convert_datetime_to_gmt} # method for customer JSON encoding of datetime fields
class CustomModel(BaseModel):
model_config = ConfigDict(
json_encoders={datetime: convert_datetime_to_gmt},
populate_by_name=True,
)

@root_validator()
def set_null_microseconds(cls, data: dict) -> dict:
"""Drops microseconds in all the datetime field values."""
@model_validator(mode="before")
@classmethod
def set_null_microseconds(cls, data: dict[str, Any]) -> dict[str, Any]:
datetime_fields = {
k: v.replace(microsecond=0)
for k, v in data.items()
Expand All @@ -453,10 +448,11 @@ class ORJSONModel(BaseModel):
return {**data, **datetime_fields}

def serializable_dict(self, **kwargs):
"""Return a dict which contains only serializable fields."""
default_dict = super().dict(**kwargs)
"""Return a dict which contains only serializable fields."""
default_dict = self.model_dump()

return jsonable_encoder(default_dict)

```
In the example above we have decided to make a global base model which:
- uses [orjson](https://github.com/ijl/orjson) to serialize data
Expand Down

0 comments on commit 1fe5dd0

Please sign in to comment.