Comments (5)
For anyone that finds this thread because they want to know how to add a root validator to a pydantic model without touching the model itself, there's one critical thing that was missing from @nazrulworld's example above. The validator function must return
the values. Here's approximately what I'm doing in my validator:
from typing import Dict
from fhir.resources.DSTU2.period import Period
from .parse_helpers import parse_end_time, parse_start_time
def normalize_period_dates(cls, values: Dict):
if not values:
return values
raw_start = values.get("start")
raw_end = values.get("end")
if raw_start:
values["start"] = parse_start_time(raw_start)
if raw_end:
values["end"] = parse_end_time(raw_end)
return values
class Shims:
_done = None
@classmethod
def setup_shims(cls):
if Shims._done:
return
# Add all root validators here
Period.add_root_validator(normalize_period_dates, pre=True)
Shims._done = True
Shims.setup_shims()
from fhir.resources.
@mmabey first of all thank you much for your help to improve the strength of this package.
However, I can explain about Date, dateTime of FHIR.
- as we know about flexibility of FHIR date format (some of incompatible with python date, datetime), to keep that in mind, fhirtypes.Date and DateTime returns string value if parts of date provided, for example only year and/or month. [we don't want loose original information in general], even DateTime type may return Date object if only year-month-day is provided.
What about business requirements like yours?
This library uses pydantic's validator strength to allow custom root validator for each model. I cannot make full documentation yet. But here example code
from fhir.resources.period import Period
def my_pre_period_validator(cls, values):
""" """
raw_start = values["start"]
raw_end = values["end"]
# do check raw values, if need add missing part of
# date. even possible to make date object
values["start"] = raw_start # modified
values["end"] = raw_end # modified
Period.add_root_validator(my_pre_period_validator, pre=True)
this function should be called my_pre_period_validator
before constructing Period object, here you will have access to raw value.
from fhir.resources.
This is a very interesting feature of pydantic, thanks for sharing!
If I'm understanding your example correctly, the modified Period
class would only be accessible to code that imported Period
from the Python file where this modification takes place, for example (assuming your example is stored in my_fhir_shim.py
):
from my_fhir_shim import Period
Is this ☝️ correct? If so, I'm not sure it helps me. For all of the FHIR objects I construct, I don't know beforehand what resource type I'm creating, so I'm making heavy use of the FHIRElementFactory
/construct_fhir_element
feature of this library.
In any case, I'm not creating Period
objects directly, they're all being created as a sub-element (sometimes a sub-sub-sub-element) of something else. For example, a Claim
resource has an Identifier
which contains a Period
. I'll make some local tests to see if it's possible to use a root validator, but if it isn't possible, do you have any other suggestions?
from fhir.resources.
I think you are almost got it, I am trying to minimize some misunderstanding. I am taking your example, the file name is my_fhir_shim .py
.
- once this
my_fhir_shim
module is imported anywhere at runtime, for example in your package root__init__.py
import my_fhir_shim
That's all! - you don't need to
from my_fhir_shim import Period
and should not worry about whether you are constructing Period manually or automatically by pedantic. All should work as expected, your function will be called before period instance creation is done. - import Period from the standard place if you are constructing manually.
- Keep in mind this should be
Period.add_root_validator(my_pre_period_validator, pre=True)
in one place across your project per function, which means the same function should not add multiple time.
from fhir.resources.
That makes so much more sense. Thank you for clarifying! It looks like it will be a while before I'm able to make another attempt at using a root validator in my project. I'll reopen if I'm unable to figure it out. Thanks again!
from fhir.resources.
Related Issues (20)
- Extend fhir.resources for a particular implementation guide HOT 2
- Adding support for FHIR R4B HOT 7
- A fan 🤩
- Better support for typing and mypy integration HOT 4
- Object gets serialized as null instead of empty dict HOT 1
- Recursive FHIR schema
- Validation error with ImagingStudy resource HOT 2
- Install to a Poetry environment HOT 2
- Incorrect parsing of StructureDefinition element ids for polymorphic elements HOT 2
- BundleEntryRequest validation error HOT 2
- Transition to R5 HOT 2
- `pkg_resources.declare_namespace` deprecation HOT 1
- urn not supported in Url
- FHIR resource as pydantic request model in FastAPI
- Pydantic 2.0 Migration Plan HOT 17
- Restrict Pydantic to <2.0.0 HOT 3
- Sample code execution error HOT 3
- Use warnings.warn() instead of logging the warning about the ignored extra parameters passed to json() and dict()
- Improve documentation of orjson HOT 1
- Parsing XML byte string MESH acknowledgment response HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fhir.resources.