This repository has been archived on 2024-10-10. You can view files and clone it, but cannot push or open issues or pull requests.
TelegramBot/classes/garbage_entry.py

74 lines
2.0 KiB
Python
Raw Permalink Normal View History

2023-08-27 23:43:16 +03:00
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
2024-05-31 00:18:33 +03:00
async def from_dict(cls, data: Mapping[str, Any]) -> "GarbageEntry":
2023-08-27 23:43:16 +03:00
"""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
2024-05-31 00:18:33 +03:00
async def from_record(cls, data: Mapping[str, Any]) -> "GarbageEntry":
2023-08-27 23:43:16 +03:00
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"],
)