|
|
from datetime import datetime |
|
|
from uuid import UUID |
|
|
|
|
|
from app.api.participants.schemas import Participant |
|
|
from app.core.config import ( |
|
|
PARTICIPANT_EXPECTED_PARTS, |
|
|
PARTICIPANT_PARSE_EMPTY_ERROR, |
|
|
PARTICIPANT_PARSE_INVALID_ERROR, |
|
|
PARTICIPANT_SEPARATOR, |
|
|
) |
|
|
|
|
|
|
|
|
class ParticipantLineParser: |
|
|
SEPARATOR = PARTICIPANT_SEPARATOR |
|
|
EXPECTED_PARTS = PARTICIPANT_EXPECTED_PARTS |
|
|
|
|
|
@classmethod |
|
|
def parse(cls, line: str) -> Participant: |
|
|
raw = line.strip() |
|
|
if not raw: |
|
|
raise ValueError(PARTICIPANT_PARSE_EMPTY_ERROR) |
|
|
|
|
|
parts = raw.split(cls.SEPARATOR) |
|
|
if len(parts) != cls.EXPECTED_PARTS: |
|
|
raise ValueError(PARTICIPANT_PARSE_INVALID_ERROR) |
|
|
|
|
|
participant_id, first_name, last_name, nickname, registered_at, activity_rating = parts |
|
|
return Participant( |
|
|
id=UUID(participant_id), |
|
|
first_name=first_name, |
|
|
last_name=last_name, |
|
|
nickname=nickname, |
|
|
registered_at=datetime.fromisoformat(registered_at), |
|
|
activity_rating=float(activity_rating), |
|
|
) |
|
|
|
|
|
@classmethod |
|
|
def serialize(cls, participant: Participant) -> str: |
|
|
return cls.SEPARATOR.join( |
|
|
[ |
|
|
str(participant.id), |
|
|
participant.first_name, |
|
|
participant.last_name, |
|
|
participant.nickname, |
|
|
participant.registered_at.isoformat(), |
|
|
f"{participant.activity_rating}", |
|
|
] |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
|