| 1 |
import dataclasses as dc |
| 2 |
import datetime |
| 3 |
import decimal |
| 4 |
import enum |
| 5 |
import ipaddress |
| 6 |
import operator |
| 7 |
import pathlib |
| 8 |
import re |
| 9 |
import uuid |
| 10 |
from collections.abc import ( |
| 11 |
Callable, |
| 12 |
Container, |
| 13 |
Iterable, |
| 14 |
Mapping, |
| 15 |
MutableMapping, |
| 16 |
) |
| 17 |
from enum import Enum |
| 18 |
from typing import Any |
| 19 |
|
| 20 |
import bson |
| 21 |
import pydantic |
| 22 |
from pydantic import AnyUrl |
| 23 |
from pydantic_core import Url |
| 24 |
|
| 25 |
import beanie |
| 26 |
from beanie.odm.fields import Link, LinkTypes |
| 27 |
from beanie.odm.utils.pydantic import ( |
| 28 |
get_model_fields, |
| 29 |
) |
| 30 |
|
| 31 |
SingleArgCallable = Callable[[Any], Any] |
| 32 |
DEFAULT_CUSTOM_ENCODERS: MutableMapping[type, SingleArgCallable] = { |
| 33 |
ipaddress.IPv4Address: str, |
| 34 |
ipaddress.IPv4Interface: str, |
| 35 |
ipaddress.IPv4Network: str, |
| 36 |
ipaddress.IPv6Address: str, |
| 37 |
ipaddress.IPv6Interface: str, |
| 38 |
ipaddress.IPv6Network: str, |
| 39 |
pathlib.PurePath: str, |
| 40 |
pydantic.SecretBytes: pydantic.SecretBytes.get_secret_value, |
| 41 |
pydantic.SecretStr: pydantic.SecretStr.get_secret_value, |
| 42 |
datetime.date: lambda d: datetime.datetime.combine(d, datetime.time.min), |
| 43 |
datetime.timedelta: operator.methodcaller("total_seconds"), |
| 44 |
enum.Enum: operator.attrgetter("value"), |
| 45 |
Link: operator.attrgetter("ref"), |
| 46 |
bytes: bson.Binary, |
| 47 |
decimal.Decimal: bson.Decimal128, |
| 48 |
uuid.UUID: bson.Binary.from_uuid, |
| 49 |
re.Pattern: bson.Regex.from_native, |
| 50 |
Url: str, |
| 51 |
AnyUrl: str, |
| 52 |
} |
| 53 |
|
| 54 |
BSON_SCALAR_TYPES = ( |
| 55 |
type(None), |
| 56 |
str, |
| 57 |
int, |
| 58 |
float, |
| 59 |
datetime.datetime, |
| 60 |
bson.Binary, |
| 61 |
bson.DBRef, |
| 62 |
bson.Decimal128, |
| 63 |
bson.MaxKey, |
| 64 |
bson.MinKey, |
| 65 |
bson.ObjectId, |
| 66 |
bson.Regex, |
| 67 |
) |
| 68 |
|
| 69 |
|
| 70 |
@dc.dataclass |
| 71 |
class Encoder: |
| 72 |
""" |
| 73 |
BSON encoding class |
| 74 |
""" |
| 75 |
|
| 76 |
exclude: Container[str] = frozenset() |
| 77 |
include: Container[str] = frozenset() |
| 78 |
custom_encoders: Mapping[type, SingleArgCallable] = dc.field( |
| 79 |
default_factory=dict |
| 80 |
) |
| 81 |
to_db: bool = False |
| 82 |
keep_nulls: bool = True |
| 83 |
|
| 84 |
def _encode_document(self, obj: "beanie.Document") -> Mapping[str, Any]: |
| 85 |
obj.parse_store() |
| 86 |
settings = obj.get_settings() |
| 87 |
obj_dict = {} |
| 88 |
if settings.union_doc is not None: |
| 89 |
obj_dict[settings.class_id] = ( |
| 90 |
settings.union_doc_alias or obj.__class__.__name__ |
| 91 |
) |
| 92 |
if obj._class_id: |
| 93 |
obj_dict[settings.class_id] = obj._class_id |
| 94 |
|
| 95 |
link_fields = obj.get_link_fields() or {} |
| 96 |
sub_encoder = Encoder( |
| 97 |
# don't propagate self.exclude to subdocuments |
| 98 |
custom_encoders=settings.bson_encoders, |
| 99 |
to_db=self.to_db, |
| 100 |
keep_nulls=self.keep_nulls, |
| 101 |
) |
| 102 |
for key, value in self._iter_model_items(obj): |
| 103 |
if key in link_fields: |
| 104 |
link_type = link_fields[key].link_type |
| 105 |
if link_type in (LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT): |
| 106 |
if value is not None: |
| 107 |
value = value.to_ref() |
| 108 |
elif link_type in (LinkTypes.LIST, LinkTypes.OPTIONAL_LIST): |
| 109 |
if value is not None: |
| 110 |
value = [link.to_ref() for link in value] |
| 111 |
elif self.to_db: |
| 112 |
continue |
| 113 |
obj_dict[key] = sub_encoder.encode(value) |
| 114 |
return obj_dict |
| 115 |
|
| 116 |
def encode(self, obj: Any) -> Any: |
| 117 |
if self.custom_encoders: |
| 118 |
encoder = _get_encoder(obj, self.custom_encoders) |
| 119 |
if encoder is not None: |
| 120 |
return encoder(obj) |
| 121 |
|
| 122 |
if isinstance(obj, BSON_SCALAR_TYPES): |
| 123 |
return obj |
| 124 |
|
| 125 |
encoder = _get_encoder(obj, DEFAULT_CUSTOM_ENCODERS) |
| 126 |
if encoder is not None: |
| 127 |
return encoder(obj) |
| 128 |
|
| 129 |
if isinstance(obj, beanie.Document): |
| 130 |
return self._encode_document(obj) |
| 131 |
if isinstance(obj, pydantic.RootModel): |
| 132 |
return self.encode(obj.root) |
| 133 |
if isinstance(obj, pydantic.BaseModel): |
| 134 |
items = self._iter_model_items(obj) |
| 135 |
return {key: self.encode(value) for key, value in items} |
| 136 |
if isinstance(obj, Mapping): |
| 137 |
return { |
| 138 |
key if isinstance(key, Enum) else str(key): self.encode(value) |
| 139 |
for key, value in obj.items() |
| 140 |
} |
| 141 |
if isinstance(obj, Iterable): |
| 142 |
return [self.encode(value) for value in obj] |
| 143 |
|
| 144 |
raise ValueError(f"Cannot encode {obj!r}") |
| 145 |
|
| 146 |
def _iter_model_items( |
| 147 |
self, obj: pydantic.BaseModel |
| 148 |
) -> Iterable[tuple[str, Any]]: |
| 149 |
keep_nulls = self.keep_nulls |
| 150 |
get_model_field = get_model_fields(obj).get |
| 151 |
for key, value in obj.__iter__(): |
| 152 |
field_info = get_model_field(key) |
| 153 |
if field_info is not None: |
| 154 |
key = field_info.alias or key |
| 155 |
if not self._should_exclude_field(key, field_info) and ( |
| 156 |
value is not None or keep_nulls |
| 157 |
): |
| 158 |
yield key, value |
| 159 |
|
| 160 |
def _should_exclude_field( |
| 161 |
self, key: str, field_info: pydantic.fields.FieldInfo | None |
| 162 |
): |
| 163 |
if key in self.include: |
| 164 |
return False |
| 165 |
|
| 166 |
is_pydantic_excluded_field = ( |
| 167 |
field_info is not None and field_info.exclude is True |
| 168 |
) |
| 169 |
return key in self.exclude or is_pydantic_excluded_field |
| 170 |
|
| 171 |
|
| 172 |
def _get_encoder( |
| 173 |
obj: Any, custom_encoders: Mapping[type, SingleArgCallable] |
| 174 |
) -> SingleArgCallable | None: |
| 175 |
encoder = custom_encoders.get(type(obj)) |
| 176 |
if encoder is not None: |
| 177 |
return encoder |
| 178 |
for cls, encoder in custom_encoders.items(): |
| 179 |
if isinstance(obj, cls): |
| 180 |
return encoder |
| 181 |
return None |