def convert_unifi_data(value: Any, field: ModelField) -> Any: """Converts value from UFP data into pydantic field class""" from pyunifiprotect.data import ( # pylint: disable=import-outside-toplevel Color, ProtectBaseObject, ) if field.shape == SHAPE_LIST and isinstance(value, list): value = [convert_unifi_data(v, field) for v in value] elif field.shape == SHAPE_DICT and isinstance(value, dict): value = {k: convert_unifi_data(v, field) for k, v in value.items()} elif field.type_ in (Union[IPv4Address, str, None], Union[IPv4Address, str]) and value is not None: try: value = IPv4Address(value) except AddressValueError: pass elif (value is None or not isclass(field.type_) or issubclass(field.type_, ProtectBaseObject) or isinstance(value, field.type_)): return value elif field.type_ in (IPv4Address, UUID, Color, Decimal, Path, Version) or issubclass(field.type_, Enum): value = field.type_(value) elif field.type_ == datetime: value = from_js_time(value) return value
def convert_unifi_data(value: Any, field: ModelField) -> Any: """Converts value from UFP data into pydantic field class""" from pyunifiprotect.data import ( # pylint: disable=import-outside-toplevel Color, ProtectBaseObject, ) if (value is None or not isclass(field.type_) or issubclass(field.type_, ProtectBaseObject) or isinstance(value, field.type_)): return value if field.shape == SHAPE_LIST and isinstance(value, list): value = [convert_unifi_data(v, field) for v in value] elif field.shape == SHAPE_DICT and isinstance(value, dict): value = {k: convert_unifi_data(v, field) for k, v in value.items()} elif field.type_ == IPv4Address: value = IPv4Address(value) elif field.type_ == UUID: value = UUID(value) elif field.type_ == datetime: value = from_js_time(value) elif field.type_ == Color: value = Color(value) elif field.type_ == Decimal: value = Decimal(value) elif field.type_ == Path: value = Path(value) elif field.type_ == Version: value = Version(value) elif issubclass(field.type_, Enum): value = field.type_(value) return value
def replace_field_type(field: ModelField): if isinstance(field.type_, type) and issubclass(field.type_, ObjectId): if field.name == 'id': field.required = True field.type_ = str elif isinstance(field.type_, type) and issubclass(field.type_, Enum): field.field_info.extra['x-enum-varnames'] = field.type_._member_names_ elif getattr(field.type_, '__origin__', None) and ObjectId in field.type_.__args__: field.type_.__args__ = tuple( map(lambda v: str if v is ObjectId else v, field.type_.__args__)) if field.sub_fields: for f in field.sub_fields: replace_field_type(f)