Skip to content

Commit

Permalink
chore: fixed open TODO[pydantic]
Browse files Browse the repository at this point in the history
For #196
  • Loading branch information
tstorek committed Jul 17, 2023
1 parent ff9b17a commit 2d87ca0
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 34 deletions.
5 changes: 2 additions & 3 deletions filip/models/ngsi_v2/registrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ class Provider(BaseModel):


class ForwardingInformation(BaseModel):
model_config = ConfigDict(frozen=True)

timesSent: int = Field(
description="(not editable, only present in GET operations): "
"Number of forwarding requests sent due to this "
Expand All @@ -61,9 +63,6 @@ class ForwardingInformation(BaseModel):
"request forwarding. Not present if registration has "
"never had a successful notification."
)
# TODO[pydantic]: The following keys were removed: `allow_mutation`.
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-config for more information.
model_config = ConfigDict(allow_mutation=False)


class DataProvided(BaseModel):
Expand Down
58 changes: 36 additions & 22 deletions filip/models/ngsi_v2/subscriptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
conint, \
Field, \
Json, \
validator
validator, model_serializer
from .base import AttrsFormat, EntityPattern, Http, Status, Expression
from filip.utils.simple_ql import QueryString, QueryStatement
from filip.utils.validators import validate_mqtt_url
Expand Down Expand Up @@ -200,24 +200,19 @@ class Notification(BaseModel):
'[A=0, B=null, C=null]. This '
)

# TODO[pydantic]: We couldn't refactor the `validator`, please replace it by `field_validator` manually.
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-validators for more information.
@validator('httpCustom')
@field_validator('httpCustom')
def validate_http(cls, http_custom, values):
if http_custom is not None:
assert values['http'] is None
return http_custom

# TODO[pydantic]: We couldn't refactor the `validator`, please replace it by `field_validator` manually.
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-validators for more information.
@validator('exceptAttrs')
@field_validator('exceptAttrs')
def validate_attr(cls, except_attrs, values):
if except_attrs is not None:
assert values['attrs'] is None
return except_attrs

@model_validator()
@classmethod
@model_validator(mode='after')
def validate_endpoints(cls, values):
if values['http'] is not None:
assert all((v is None for k, v in values.items() if k in [
Expand Down Expand Up @@ -289,18 +284,23 @@ class Condition(BaseModel):
)

@field_validator('attrs')
@classmethod
def check_attrs(cls, v):
if isinstance(v, list):
return v
elif isinstance(v, str):
return [v]
else:
raise TypeError()
# TODO[pydantic]: The following keys were removed: `json_encoders`.
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-config for more information.
model_config = ConfigDict(json_encoders={QueryString: lambda v: v.to_str(),
QueryStatement: lambda v: v.to_str()})

@model_serializer
def serialize(self):
dump = {}
for k, v in self:
if isinstance(v, (QueryString, QueryStatement)):
dump.update({k: v.to_str()})
else:
dump.update({k: v})
return dump


class Subject(BaseModel):
Expand All @@ -314,17 +314,25 @@ class Subject(BaseModel):
condition: Optional[Condition] = Field(
default=None,
)
# TODO[pydantic]: The following keys were removed: `json_encoders`.
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-config for more information.
model_config = ConfigDict(json_encoders={QueryString: lambda v: v.to_str(),
QueryStatement: lambda v: v.to_str()})

@model_serializer
def serialize(self):
dump = {}
for k, v in self:
if isinstance(v, (QueryString, QueryStatement)):
dump.update({k: v.to_str()})
else:
dump.update({k: v})
return dump


class Subscription(BaseModel):
"""
Subscription payload validations
https://fiware-orion.readthedocs.io/en/master/user/ngsiv2_implementation_notes/index.html#subscription-payload-validations
"""
model_config = ConfigDict(validate_assignment=True)

id: Optional[str] = Field(
default=None,
description="Subscription unique identifier. Automatically created at "
Expand Down Expand Up @@ -379,7 +387,13 @@ class Subscription(BaseModel):
"must elapse between two consecutive notifications. "
"It is optional."
)
# TODO[pydantic]: The following keys were removed: `json_encoders`.
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-config for more information.
model_config = ConfigDict(validate_assignment=True, json_encoders={QueryString: lambda v: v.to_str(),
QueryStatement: lambda v: v.to_str()})

@model_serializer
def serialize(self):
dump = {}
for k, v in self:
if isinstance(v, (QueryString, QueryStatement)):
dump.update({k: v.to_str()})
else:
dump.update({k: v})
return dump
16 changes: 7 additions & 9 deletions filip/semantics/semantics_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ class DeviceProperty(BaseModel):
A property can only belong to one field of one instance. Assigning it to
multiple fields will result in an error.
"""
model_config = ConfigDict()

name: str = Field("Internally used name in the IoT Device")
_instance_link: DevicePropertyInstanceLink = DevicePropertyInstanceLink()
Expand Down Expand Up @@ -225,9 +226,8 @@ def get_all_field_names(self, field_name: Optional[str] = None) \
is used
"""
pass
# TODO[pydantic]: The following keys were removed: `underscore_attrs_are_private`.
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-config for more information.
model_config = ConfigDict(underscore_attrs_are_private=True)




class Command(DeviceProperty):
Expand Down Expand Up @@ -357,6 +357,7 @@ class Field(BaseModel):
The fields of a class are predefined. A field can contain standard values
on init
"""
model_config = ConfigDict()

name: str = Field(
default="",
Expand Down Expand Up @@ -588,9 +589,8 @@ def __iter__(self) -> Iterator[Any]:
Overrides the magic "in" to loop over the field values
"""
return self.get_all().__iter__()
# TODO[pydantic]: The following keys were removed: `underscore_attrs_are_private`.
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-config for more information.
model_config = ConfigDict(underscore_attrs_are_private=True)




class DeviceField(Field):
Expand Down Expand Up @@ -1528,6 +1528,7 @@ def build_context_entity(self) -> ContextEntity:
Returns:
ContextEntity
"""
model_config = ConfigDict(arbitrary_types_allowed=True, frozen=True)

entity = ContextEntity(
id=self.id,
Expand Down Expand Up @@ -1572,9 +1573,6 @@ def get_all_field_names(self) -> List[str]:
for field in self.get_fields():
res.extend(field.get_field_names())
return res
# TODO[pydantic]: The following keys were removed: `allow_mutation`, `underscore_attrs_are_private`.
# Check https://docs.pydantic.dev/dev-v2/migration/#changes-to-config for more information.
model_config = ConfigDict(arbitrary_types_allowed=True, allow_mutation=False, frozen=True, underscore_attrs_are_private=True)

def __str__(self):
return str(self.dict(exclude={'semantic_manager', 'old_state'}))
Expand Down

0 comments on commit 2d87ca0

Please sign in to comment.