Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Use fhirdatetime instead of Pydantic's datetime #68

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 20 additions & 23 deletions fhir/resources/DSTU2/fhirtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import TYPE_CHECKING, Any, Dict, Optional, Pattern, Union
from uuid import UUID

from fhirdatetime import FhirDateTime
from pydantic import AnyUrl
from pydantic.errors import DateError, DateTimeError, TimeError
from pydantic.main import load_str_bytes
Expand All @@ -16,7 +17,7 @@
ConstrainedInt,
ConstrainedStr,
)
from pydantic.validators import bool_validator, parse_date, parse_datetime, parse_time
from pydantic.validators import bool_validator, parse_time

from .fhirabstractmodel import FHIRAbstractModel
from .fhirtypesvalidators import run_validator_for_fhir_type
Expand Down Expand Up @@ -248,7 +249,7 @@ class Xhtml(ConstrainedStr):
__visit_name__ = "xhtml"


class Date(datetime.date):
class Date(FhirDateTime):
"""A date, or partial date (e.g. just year or year + month)
as used in human communication. The format is YYYY, YYYY-MM, or YYYY-MM-DD,
e.g. 2018, 1973-06, or 1905-08-23.
Expand All @@ -268,12 +269,12 @@ def __get_validators__(cls) -> "CallableGenerator":

@classmethod
def validate(
cls, value: Union[datetime.date, str, bytes, int, float]
) -> Union[datetime.date, str]:
cls, value: Union[FhirDateTime, datetime.date, str, bytes, int, float]
) -> FhirDateTime:
""" """
if not isinstance(value, str):
# default handler
return parse_date(value)
return FhirDateTime(value)

match = FHIR_DATE_PARTS.match(value)

Expand All @@ -283,12 +284,10 @@ def validate(
elif not match.groupdict().get("day"):
if match.groupdict().get("month") and int(match.groupdict()["month"]) > 12:
raise DateError()
# we keep original
return value
return parse_date(value)
return FhirDateTime(value)


class DateTime(datetime.datetime):
class DateTime(FhirDateTime):
"""A date, date-time or partial date (e.g. just year or year + month) as used
in human communication. The format is YYYY, YYYY-MM, YYYY-MM-DD or
YYYY-MM-DDThh:mm:ss+zz:zz, e.g. 2018, 1973-06, 1905-08-23,
Expand All @@ -315,35 +314,33 @@ def __get_validators__(cls) -> "CallableGenerator":

@classmethod
def validate(
cls, value: Union[datetime.date, datetime.datetime, str, bytes, int, float]
) -> Union[datetime.datetime, datetime.date, str]:
cls,
value: Union[
FhirDateTime, datetime.date, datetime.datetime, str, bytes, int, float
],
) -> FhirDateTime:
""" """
if isinstance(value, datetime.date):
return value

if not isinstance(value, str):
if isinstance(value, datetime.date) or not isinstance(value, str):
# default handler
return parse_datetime(value)
return FhirDateTime(value)
match = FHIR_DATE_PARTS.match(value)
if match:
if (
match.groupdict().get("year")
and match.groupdict().get("month")
and match.groupdict().get("day")
):
return parse_date(value)
return FhirDateTime(value)
elif match.groupdict().get("year") and match.groupdict().get("month"):
if int(match.groupdict()["month"]) > 12:
raise DateError()
# we don't want to loose actual information, so keep as string
return value
if not cls.regex.match(value):
raise DateTimeError()

return parse_datetime(value)
return FhirDateTime(value)


class Instant(datetime.datetime):
class Instant(FhirDateTime):
"""An instant in time in the format YYYY-MM-DDThh:mm:ss.sss+zz:zz
(e.g. 2015-02-07T13:28:17.239+02:00 or 2017-01-01T00:00:00Z).
The time SHALL specified at least to the second and SHALL include a time zone.
Expand All @@ -369,12 +366,12 @@ def __get_validators__(cls) -> "CallableGenerator":
yield cls.validate

@classmethod
def validate(cls, value):
def validate(cls, value) -> FhirDateTime:
""" """
if isinstance(value, str):
if not cls.regex.match(value):
raise DateTimeError()
return parse_datetime(value)
return FhirDateTime(value)


class Time(datetime.time):
Expand Down
14 changes: 6 additions & 8 deletions fhir/resources/DSTU2/tests/test_allergyintolerance.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
from pydantic.datetime_parse import parse_date, parse_datetime

from .. import fhirtypes # noqa: F401
from .. import allergyintolerance

Expand Down Expand Up @@ -43,7 +41,7 @@ def impl_AllergyIntolerance_1(inst):
assert inst.identifier[0].system == "http://acme.com/ids/patients/risks"
assert inst.identifier[0].value == "49476534"
assert inst.patient.reference == "Patient/example"
assert inst.recordedDate == parse_datetime("2014-10-09T14:58:00+11:00")
assert inst.recordedDate.isoformat() == "2014-10-09T14:58:00+11:00"
assert inst.recorder.reference == "Practitioner/example"
assert inst.status == "refuted"
assert inst.substance.coding[0].code == "227493005"
Expand Down Expand Up @@ -94,7 +92,7 @@ def impl_AllergyIntolerance_2(inst):
assert (
inst.reaction[0].manifestation[0].coding[0].system == "http://snomed.info/sct"
)
assert inst.reaction[0].onset == parse_date("2012-06-12")
assert str(inst.reaction[0].onset) == "2012-06-12"
assert inst.reaction[0].severity == "severe"
assert inst.reaction[0].substance.coding[0].code == "C3214954"
assert (
Expand All @@ -111,9 +109,9 @@ def impl_AllergyIntolerance_2(inst):
assert (
inst.reaction[1].manifestation[0].coding[0].system == "http://snomed.info/sct"
)
assert inst.reaction[1].onset == "2004"
assert str(inst.reaction[1].onset) == "2004"
assert inst.reaction[1].severity == "moderate"
assert inst.recordedDate == parse_datetime("2014-10-09T14:58:00+11:00")
assert inst.recordedDate.isoformat() == "2014-10-09T14:58:00+11:00"
assert inst.recorder.reference == "Practitioner/example"
assert inst.status == "confirmed"
assert inst.substance.coding[0].code == "227493005"
Expand Down Expand Up @@ -152,7 +150,7 @@ def impl_AllergyIntolerance_3(inst):
assert inst.identifier[0].system == "http://acme.com/ids/patients/risks"
assert inst.identifier[0].value == "49476535"
assert inst.patient.reference == "Patient/example"
assert inst.recordedDate == parse_datetime("2015-08-06T15:37:31-06:00")
assert inst.recordedDate.isoformat() == "2015-08-06T15:37:31-06:00"
assert inst.recorder.reference == "Practitioner/example"
assert inst.substance.coding[0].code == "227037002"
assert inst.substance.coding[0].display == "Fish - dietary (substance)"
Expand Down Expand Up @@ -198,7 +196,7 @@ def impl_AllergyIntolerance_4(inst):
assert (
inst.reaction[0].manifestation[0].coding[0].system == "http://snomed.info/sct"
)
assert inst.recordedDate == parse_date("2010-03-01")
assert str(inst.recordedDate) == "2010-03-01"
assert inst.recorder.reference == "Practitioner/13"
assert inst.status == "unconfirmed"
assert inst.substance.coding[0].code == "314422"
Expand Down
43 changes: 20 additions & 23 deletions fhir/resources/STU3/fhirtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import TYPE_CHECKING, Any, Dict, Optional, Pattern, Union
from uuid import UUID

from fhirdatetime import FhirDateTime
from pydantic import AnyUrl
from pydantic.errors import DateError, DateTimeError, TimeError
from pydantic.main import load_str_bytes
Expand All @@ -16,7 +17,7 @@
ConstrainedInt,
ConstrainedStr,
)
from pydantic.validators import bool_validator, parse_date, parse_datetime, parse_time
from pydantic.validators import bool_validator, parse_time

from .fhirabstractmodel import FHIRAbstractModel
from .fhirtypesvalidators import run_validator_for_fhir_type
Expand Down Expand Up @@ -289,7 +290,7 @@ class Xhtml(ConstrainedStr, Primitive):
__visit_name__ = "xhtml"


class Date(datetime.date, Primitive):
class Date(FhirDateTime, Primitive):
"""A date, or partial date (e.g. just year or year + month)
as used in human communication. The format is YYYY, YYYY-MM, or YYYY-MM-DD,
e.g. 2018, 1973-06, or 1905-08-23.
Expand All @@ -309,12 +310,12 @@ def __get_validators__(cls) -> "CallableGenerator":

@classmethod
def validate(
cls, value: Union[datetime.date, str, bytes, int, float]
) -> Union[datetime.date, str]:
cls, value: Union[FhirDateTime, datetime.date, str, bytes, int, float]
) -> FhirDateTime:
""" """
if not isinstance(value, str):
# default handler
return parse_date(value)
return FhirDateTime(value)

match = FHIR_DATE_PARTS.match(value)

Expand All @@ -324,12 +325,10 @@ def validate(
elif not match.groupdict().get("day"):
if match.groupdict().get("month") and int(match.groupdict()["month"]) > 12:
raise DateError()
# we keep original
return value
return parse_date(value)
return FhirDateTime(value)


class DateTime(datetime.datetime, Primitive):
class DateTime(FhirDateTime, Primitive):
"""A date, date-time or partial date (e.g. just year or year + month) as used
in human communication. The format is YYYY, YYYY-MM, YYYY-MM-DD or
YYYY-MM-DDThh:mm:ss+zz:zz, e.g. 2018, 1973-06, 1905-08-23,
Expand All @@ -356,35 +355,33 @@ def __get_validators__(cls) -> "CallableGenerator":

@classmethod
def validate(
cls, value: Union[datetime.date, datetime.datetime, str, bytes, int, float]
) -> Union[datetime.datetime, datetime.date, str]:
cls,
value: Union[
FhirDateTime, datetime.date, datetime.datetime, str, bytes, int, float
],
) -> FhirDateTime:
""" """
if isinstance(value, datetime.date):
return value

if not isinstance(value, str):
if isinstance(value, datetime.date) or not isinstance(value, str):
# default handler
return parse_datetime(value)
return FhirDateTime(value)
match = FHIR_DATE_PARTS.match(value)
if match:
if (
match.groupdict().get("year")
and match.groupdict().get("month")
and match.groupdict().get("day")
):
return parse_date(value)
return FhirDateTime(value)
elif match.groupdict().get("year") and match.groupdict().get("month"):
if int(match.groupdict()["month"]) > 12:
raise DateError()
# we don't want to loose actual information, so keep as string
return value
if not cls.regex.match(value):
raise DateTimeError()

return parse_datetime(value)
return FhirDateTime(value)


class Instant(datetime.datetime, Primitive):
class Instant(FhirDateTime, Primitive):
"""An instant in time in the format YYYY-MM-DDThh:mm:ss.sss+zz:zz
(e.g. 2015-02-07T13:28:17.239+02:00 or 2017-01-01T00:00:00Z).
The time SHALL specified at least to the second and SHALL include a time zone.
Expand All @@ -410,12 +407,12 @@ def __get_validators__(cls) -> "CallableGenerator":
yield cls.validate

@classmethod
def validate(cls, value):
def validate(cls, value) -> FhirDateTime:
""" """
if isinstance(value, str):
if not cls.regex.match(value):
raise DateTimeError()
return parse_datetime(value)
return FhirDateTime(value)


class Time(datetime.time, Primitive):
Expand Down
Loading