def import_string(dotted_path: str) -> type: """Shameless hack from django utils, please don't mind!""" module_path, class_name = None, None try: module_path, class_name = dotted_path.rsplit(".", 1) except (ValueError, AttributeError): t, v, tb = sys.exc_info() msg = "{0} doesn't look like a module path".format(dotted_path) try: reraise(ImportError(msg), None, tb) finally: del t, v, tb module = import_module(module_path) try: return getattr(module, class_name) except AttributeError: msg = 'Module "{0}" does not define a "{1}" attribute/class'.format( module_path, class_name ) t, v, tb = sys.exc_info() try: return reraise(ImportError(msg), None, tb) finally: del t, v, tb
def _validate_object(self, obj: FhirResourceType = None): # noqa: E999 """ """ if obj is None: return try: verifyObject(IFhirResource, obj, False) except (BrokenImplementation, BrokenMethodImplementation): t, v, tb = sys.exc_info() try: reraise(Invalid(str(v)), None, tb) finally: del t, v, tb except DoesNotImplement: msg = "Object must be derived from valid FHIR resource class!" msg += "But it is found that object is derived from `{0}`".format( obj.__class__.__module__ + "." + obj.__class__.__name__) t, v, tb = sys.exc_info() msg += "\nOriginal Exception: {0!s}".format(str(v)) try: reraise(WrongType(msg), None, tb) finally: del t, v, tb
def patch(self, patch_data): if not isinstance(patch_data, (list, tuple)): raise WrongType( "patch value must be list or tuple type! but got `{0}` type.". format(type(patch_data))) if not bool(self): raise Invalid( "None object cannot be patched! Make sure fhir resource value is not empty!" ) try: patcher = jsonpatch.JsonPatch(patch_data) value = patcher.apply(self._resource_obj.as_json()) new_value = self._resource_obj.__class__(value) object.__setattr__(self, "_resource_obj", new_value) except jsonpatch.JsonPatchException: t, v, tb = sys.exc_info() try: reraise(Invalid(str(v)), None, tb) finally: del t, v, tb
def validate_resource_type(resource_type: str) -> NoneType: """FHIR resource type validation""" try: FHIR_RESOURCE_LIST[resource_type.lower()] except KeyError: msg = ( f"{resource_type} is not valid FHIR Resource! " "@see: https://hl7.org/fhir/" ) t, v, tb = sys.exc_info() try: reraise(Invalid(msg), None, tb) finally: del t, v, tb
def parse_json_str(str_val: str) -> Union[dict, NoneType]: """ """ if str_val in (EMPTY_VALUE, EMPTY_STRING, None): # No parsing for empty value return None try: json_dict = json.loads(str_val) except ValueError as exc: msg = "Invalid JSON String is provided!\n{0!s}".format(exc) t, v, tb = sys.exc_info() try: reraise(Invalid(msg), None, tb) finally: del t, v, tb return json_dict
def _validate(self, value): """ """ super(FhirField, self)._validate(value) if self.resource_interface: try: verifyObject(self._resource_interface_class, value.foreground_origin(), False) except (BrokenImplementation, BrokenMethodImplementation, DoesNotImplement): t, v, tb = sys.exc_info() try: reraise(Invalid(str(v)), None, tb) finally: del t, v, tb if self.resource_type and value.resource_type != self.resource_type: msg = "Resource type must be `{0}` but we got {1} which is not allowed!".format( self.resource_type, value.resource_type) raise ConstraintNotSatisfied(msg) if self.resource_class: klass = self._resource_class if value.foreground_origin() is not None and not isinstance( value.foreground_origin(), klass): msg = "Wrong fhir resource value is provided! "\ "Value should be object of {0!r} but got {1!r}".\ format(klass, value.foreground_origin().__class__) raise WrongContainedType(msg) if value.foreground_origin() is not None: try: value.foreground_origin().as_json() except (FHIRValidationError, TypeError) as exc: msg = "There is invalid element inside fhir model object.\n{0!s}".format( exc) t, v, tb = sys.exc_info() try: reraise(Invalid(msg), None, tb) finally: del t, v, tb
def fhir_resource_mapping(resource_type: str, cache: bool = True) -> dict: """""" if resource_type in FHIR_ES_MAPPINGS_CACHE and cache: return FHIR_ES_MAPPINGS_CACHE[resource_type] try: FHIR_RESOURCE_LIST[resource_type.lower()] except KeyError: msg = f"{resource_type} is not valid FHIR resource type" t, v, tb = sys.exc_info() try: reraise(Invalid(msg), None, tb) finally: del t, v, tb mapping_json = FHIR_RESOURCE_MAPPING_DIR / f"{resource_type}.mapping.json" if not mapping_json.exists(): warnings.warn( f"Mapping for {resource_type} is currently not supported," " default Resource's mapping is used instead!", UserWarning, ) return fhir_resource_mapping("Resource", cache=True) with io.open(str(mapping_json), "r", encoding="utf8") as f: mapping_dict = ujson.load(f) # xxx: validate mapping_dict['meta']['profile']? FHIR_ES_MAPPINGS_CACHE[resource_type] = mapping_dict["mapping"] return FHIR_ES_MAPPINGS_CACHE[resource_type]
def _init(self, resource_class, resource_interface, resource_type, **kw): """ """ if "default" in kw: if (isinstance(kw["default"], (str, dict)) or kw["default"] is None) is False: msg = ("Only dict or string or None is accepted as " "default value but got {0}".format(type(kw["default"]))) raise Invalid(msg) field_attributes = get_fields(IFhirField) attribute = field_attributes['resource_class'].bind(self) if resource_class is None: attribute.validate(resource_class) attribute_val = None else: attribute_val = attribute.from_unicode(resource_class) attribute.set(self, attribute_val) attribute = field_attributes['resource_interface'].bind(self) if resource_interface is None: attribute.validate(resource_interface) attribute_val = None else: attribute_val = attribute.from_unicode(resource_interface) attribute.set(self, attribute_val) attribute = field_attributes['resource_type'].bind(self) if resource_type is None: attribute.validate(resource_type) attribute_val = None else: attribute_val = attribute.from_unicode(resource_type) attribute.set(self, attribute_val) if self.resource_type and self.resource_class is not None: raise Invalid( "Either `resource_class` or `resource_type` value is acceptable! you cannot provide both!" ) if self.resource_class: try: klass = import_string(self.resource_class) except ImportError: msg = "Invalid FHIR Resource class `{0}`! Please check the module or class name.".format( self.resource_class) t, v, tb = sys.exc_info() try: reraise(Invalid(msg), None, tb) finally: del t, v, tb if not IFhirResource.implementedBy(klass): raise Invalid( "{0!r} must be valid resource class from fhir.resources". format(klass)) self._resource_class = klass if self.resource_type: try: self._resource_class = resource_type_to_resource_cls( self.resource_type) except ImportError: msg = "{0} is not valid fhir resource type!".format( self.resource_type) t, v, tb = sys.exc_info() try: reraise(Invalid(msg), None, tb) finally: del t, v, tb raise Invalid(msg) if self.resource_interface: try: klass = import_string(self.resource_interface) except ImportError: msg = "Invalid FHIR Resource Interface`{0}`! Please check the module or class name.".format( self.resource_interface) t, v, tb = sys.exc_info() try: reraise(Invalid(msg), None, tb) finally: del t, v, tb if not IInterface.providedBy(klass): raise WrongType("An interface is required", klass, self.__name__) if klass is not IFhirResource and not issubclass( klass, IFhirResource): msg = "`{0!r}` must be derived from {1}".format( klass, IFhirResource.__module__ + "." + IFhirResource.__class__.__name__, ) raise Invalid(msg) self._resource_interface_class = klass