74 lines
2.0 KiB
Python
74 lines
2.0 KiB
Python
from dataclasses import dataclass
|
|
from datetime import datetime
|
|
from typing import Any, List, Mapping, Union
|
|
|
|
from bson import ObjectId
|
|
|
|
from classes.enums.garbage_type import GarbageType
|
|
from classes.location import Location
|
|
|
|
|
|
@dataclass
|
|
class GarbageEntry:
|
|
__slots__ = (
|
|
"_id",
|
|
"locations",
|
|
"garbage_type",
|
|
"date",
|
|
)
|
|
|
|
_id: Union[ObjectId, None]
|
|
locations: List[Location]
|
|
garbage_type: GarbageType
|
|
date: datetime
|
|
|
|
@classmethod
|
|
async def from_dict(cls, data: Mapping[str, Any]) -> "GarbageEntry":
|
|
"""Generate GarbageEntry object from the mapping provided
|
|
|
|
### Args:
|
|
* data (`Mapping[str, Any]`): Entry
|
|
|
|
### Raises:
|
|
* `KeyError`: Key is missing.
|
|
* `TypeError`: Key of a wrong type provided.
|
|
* `ValueError`: "date" is not a valid ISO string.
|
|
|
|
### Returns:
|
|
* `GarbageEntry`: Valid GarbageEntry object.
|
|
"""
|
|
for key in ("locations", "garbage_type", "date"):
|
|
if key not in data:
|
|
raise KeyError
|
|
if key == "locations" and not isinstance(data[key], list):
|
|
raise TypeError
|
|
if key == "garbage_type" and not isinstance(data[key], int):
|
|
raise TypeError
|
|
if key == "date":
|
|
datetime.fromisoformat(str(data[key]))
|
|
|
|
locations = [
|
|
await Location.get(location_id) for location_id in data["locations"]
|
|
]
|
|
garbage_type = GarbageType(data["garbage_type"])
|
|
|
|
return cls(
|
|
None,
|
|
locations,
|
|
garbage_type,
|
|
data["date"],
|
|
)
|
|
|
|
@classmethod
|
|
async def from_record(cls, data: Mapping[str, Any]) -> "GarbageEntry":
|
|
locations = [
|
|
await Location.get(location_id) for location_id in data["locations"]
|
|
]
|
|
garbage_type = GarbageType(data["garbage_type"])
|
|
return cls(
|
|
data["_id"],
|
|
locations,
|
|
garbage_type,
|
|
data["date"],
|
|
)
|