data_models: fix a data parsing bug

This commit is contained in:
Sina Atalay 2024-05-17 15:29:17 +03:00
parent 3679684264
commit c91e319230
1 changed files with 27 additions and 15 deletions

View File

@ -193,7 +193,7 @@ class EntryWithDate(RenderCVBaseModel):
examples=["2020-09-24", "Fall 2023"], examples=["2020-09-24", "Fall 2023"],
) )
@pydantic.field_validator("date") @pydantic.field_validator("date", mode="before")
@classmethod @classmethod
def check_date( def check_date(
cls, date: Optional[int | RenderCVDate | str] cls, date: Optional[int | RenderCVDate | str]
@ -201,19 +201,25 @@ class EntryWithDate(RenderCVBaseModel):
"""Check if the date is provided correctly.""" """Check if the date is provided correctly."""
date_is_provided = date is not None date_is_provided = date is not None
if date_is_provided and isinstance(date, str): if date_is_provided:
date_pattern = r"\d{4}(-\d{2})?(-\d{2})?" if isinstance(date, str):
if re.fullmatch(date_pattern, date): date_pattern = r"\d{4}(-\d{2})?(-\d{2})?"
# Then it is in YYYY-MM-DD, YYYY-MM, or YYYY format if re.fullmatch(date_pattern, date):
# Check if it is a valid date: # Then it is in YYYY-MM-DD, YYYY-MM, or YYYY format
get_date_object(date) # Check if it is a valid date:
get_date_object(date)
# check if it is in YYYY format, and if so, convert it to an integer: # check if it is in YYYY format, and if so, convert it to an
if re.fullmatch(r"\d{4}", date): # integer:
# This is not required for start_date and end_date because they if re.fullmatch(r"\d{4}", date):
# can't be casted into a general string. For date, this needs to be # This is not required for start_date and end_date because they
# done manually, because it can be a general string. # can't be casted into a general string. For date, this needs to
date = int(date) # be done manually, because it can be a general string.
date = int(date)
elif isinstance(date, Date):
# Pydantic parses YYYY-MM-DD dates as datetime.date objects. We need to
# convert them to strings because that's how RenderCV uses them.
date = date.isoformat()
return date return date
@ -323,7 +329,7 @@ class EntryBase(EntryWithDate):
examples=["Did this.", "Did that."], examples=["Did this.", "Did that."],
) )
@pydantic.field_validator("start_date", "end_date") @pydantic.field_validator("start_date", "end_date", mode="before")
@classmethod @classmethod
def check_and_parse_dates( def check_and_parse_dates(
cls, cls,
@ -332,7 +338,13 @@ class EntryBase(EntryWithDate):
date_is_provided = date is not None date_is_provided = date is not None
if date_is_provided: if date_is_provided:
if date != "present": if isinstance(date, Date):
# Pydantic parses YYYY-MM-DD dates as datetime.date objects. We need to
# convert them to strings because that's how RenderCV uses them.
date = date.isoformat()
elif date != "present":
# Validate the date:
get_date_object(date) get_date_object(date)
return date return date