Skip to content
This repository has been archived by the owner on Jan 18, 2025. It is now read-only.

Commit

Permalink
fix(GetData): resolve mutiples error of async in GetData
Browse files Browse the repository at this point in the history
  • Loading branch information
NTGNguyen committed Dec 30, 2024
1 parent 9ee9de9 commit d8820b0
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
11 changes: 10 additions & 1 deletion src/check_phat_nguoi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import asyncio
from logging import Logger, getLogger

from check_phat_nguoi.config import config
from check_phat_nguoi.config.config_reader import _config_reader
from check_phat_nguoi.get_data.check_phat_nguoi import GetDataCheckPhatNguoi

from .utils.setup_logger import setup_logger

logger: Logger = getLogger(__name__)


def main() -> None:
async def _main():
setup_logger()
logger.debug(config)
get_data_object = GetDataCheckPhatNguoi(_config_reader().data)
data = await get_data_object.get_data()


def main():
asyncio.run(_main())


__all__ = ["main"]
8 changes: 8 additions & 0 deletions src/check_phat_nguoi/config/dto/plate_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,13 @@ class PlateInfoDTO(BaseModel):
default=None,
)

def __hash__(self):
return hash(self.plate)

def __eq__(self, other):
if isinstance(other, PlateInfoDTO):
return self.plate == other.plate
return False


__all__ = ["PlateInfoDTO"]
15 changes: 10 additions & 5 deletions src/check_phat_nguoi/get_data/check_phat_nguoi.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import json
import re
from datetime import datetime
from logging import getLogger
Expand Down Expand Up @@ -28,22 +29,23 @@ def __init__(
) -> None:
super().__init__(plate_infos)
self.data_dict: Dict[PlateInfoDTO, None | Dict] = {}
self.session = ClientSession()
self.timeout = timeout
self.headers = {"Content-Type": "application/json"}

async def _get_data_request(self, plate_info_object: PlateInfoDTO) -> None:
payload: dict[str, str] = {"bienso": plate_info_object.plate}
session = ClientSession()
try:
async with self.session.post(
async with session.post(
API_URL,
headers=self.headers,
json=payload,
timeout=ClientTimeout(self.timeout),
) as response:
response.raise_for_status()

response_data: Dict = await response.json()
response_data = await response.read()
response_data = json.loads(response_data)
self.data_dict[plate_info_object] = response_data
except asyncio.TimeoutError:
logger.error(
Expand All @@ -53,6 +55,8 @@ async def _get_data_request(self, plate_info_object: PlateInfoDTO) -> None:
logger.error(
f"Error occurs while connecting to {API_URL} for plate: {plate_info_object.plate}"
)
finally:
await session.close()

async def _get_data(self) -> None:
tasks = [self._get_data_request(plate_info) for plate_info in self._plate_infos]
Expand All @@ -64,6 +68,8 @@ def get_plate_violation(
) -> tuple[ViolationModel, ...]:
if plate_violation_dict is None:
return ()
if plate_violation_dict["data"] is None:
return ()

def _create_resolution_office_mode(
resolution_offices: list[str],
Expand Down Expand Up @@ -100,7 +106,7 @@ def _create_violation_model(data: Dict):
date=datetime.strptime(data["Thời gian vi phạm"], DATETIME_FORMAT),
location=data["Địa điểm vi phạm"],
action=data["Hành vi vi phạm"],
status=data["Trạng thái"],
status=False if data["Trạng thái"] == "Chưa xử phạt" else True,
enforcement_unit=data["Đơn vị phát hiện vi phạm"],
resolution_office=_create_resolution_office_mode(
data["Nơi giải quyết vụ việc"]
Expand All @@ -125,6 +131,5 @@ async def get_data(self) -> tuple[PlateInfoModel, ...]:
)
for plate_info_object, plate_violation_dict in self.data_dict.items()
)
await self.session.close()

return plate_infos

0 comments on commit d8820b0

Please sign in to comment.