def patient_to_individual(obj): """ FHIR Patient to Individual. """ patient = p.Patient(obj) individual = {"id": patient.id} if patient.identifier: individual["alternate_ids"] = [ alternate_id.value for alternate_id in patient.identifier ] gender_to_sex = { "male": "MALE", "female": "FEMALE", "other": "OTHER_SEX", "unknown": "UNKNOWN_SEX" } if patient.gender: individual["sex"] = gender_to_sex[patient.gender] if patient.birthDate: individual["date_of_birth"] = patient.birthDate.isostring if patient.active: individual["active"] = patient.active if patient.deceasedBoolean: individual["deceased"] = patient.deceasedBoolean individual["extra_properties"] = patient.as_json() return individual
def create_patient(base_url, project_id, cloud_region, dataset_id, fhir_store_id): """Creates a new Patient resource in a FHIR store.""" url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region) fhir_store_path = "{}/datasets/{}/fhirStores/{}/fhir/Patient".format( url, dataset_id, fhir_store_id) # Make an authenticated API request session = get_session() headers = {"Content-Type": "application/fhir+json;charset=utf-8"} patient = p.Patient({'id': 'patient-1'}) # body = { # "name": [{"use": "official", "family": "Smith", "given": ["Darcy"]}], # "gender": "female", # "birthDate": "1970-01-01", # "resourceType": "Patient", # } body = patient.as_json() response = session.post(fhir_store_path, headers=headers, json=body) response.raise_for_status() resource = response.json() print("Created Patient resource with ID {}".format(resource["id"])) return response
def patient_list(): start = request.args.get('start', 0) length = request.args.get('length', 100) start = int(start) length = int(length) count = db.engine.execute("select count(*) from T_Patients").scalar() result = db.engine.execute("select * from T_Patients limit %d, %d" % (start, length)) plist = [] total = count for row in result: patient = p.Patient({'id': row['pat_id']}) name = hn.HumanName() name.given = [row['pat_first']] name.family = row['pat_last'] patient.name = [name] address = addr.Address() address.city = row['pat_city'] address.state = row['pat_state'] address.postalCode = row['pat_zip'] address.district = row['pat_address'] patient.address = [address] patient.gender = row['pat_gender'] patient.birthDate = fd.FHIRDate( datetime.strftime(row['pat_birthdate'], "%Y-%m-%d")) # patient.maritalStatus = row['pat_marital'] plist.append(patient.as_json()) return jsonify(results=plist, total=total)
def patient(id): # https://{FHIR Base URL}/Patient/{id}? # name={name}& # family={family name}& # gender={gender}& # _format=json # TODO: query params name = request.args.get('name', None) family = request.args.get('family', None) gender = request.args.get('gender', None) # TODO: connect to database to search patient result = db.engine.execute("select * from T_Patients limit 1") names = [] for row in result: patient = p.Patient({'id': row['pat_id']}) name = hn.HumanName() name.given = [row['pat_first']] name.family = row['pat_last'] patient.name = [name] address = addr.Address() address.city = row['pat_city'] address.state = row['pat_state'] address.postalCode = row['pat_zip'] address.district = row['pat_address'] patient.address = [address] patient.gender = row['pat_gender'] patient.birthDate = fd.FHIRDate( datetime.strftime(row['pat_birthdate'], "%Y-%m-%d")) patient.maritalStatus = row['pat_marital'] return jsonify(result=patient.as_json())
def addPatientToServer(self, given_name, family_name): patient = p.Patient() name = hn.HumanName() name.given = [given_name] name.family = [family_name] patient.name = [name] result_json = patient.create(self.smart.server) patient.id = self.getCreatedId(result_json) return patient.id
def fhir(): import fhirclient.models.patient as p import fhirclient.models.humanname as hn patient = p.Patient({'id': 'patient-1'}) print(patient.id) # prints `patient-1` name = hn.HumanName() name.given = ['Peter'] name.family = 'Parker' patient.name = [name] print(mongodb) print(patient.as_json()) dict01 = patient.as_json() ret = mongodb.a.insert_one(dict01) print(ret) ret = mongodb.a.find() for i in ret: print(i) print('111111111111111111') import json import fhirclient.models.patient as p with open('/home/python/Desktop/odk/patient-example.json', 'r') as h: pjs = json.load(h) patient = p.Patient(pjs) dict02 = patient.as_json() ret = mongodb.a.insert_one(dict02) print(ret) ret = mongodb.a.find() for i in ret: print(i) print('2222222222222222') print(patient.name[0].given) print(patient.name) print(patient.gender) print(patient.photo) print(patient.address) print("-------------------------") # prints patient's given name array in the first `name` property return ret_data(200, '请求成功', 1000)
def read_json_patient(path): """ INPUTS: path: path to example json file OUTPUT: the patient object """ with open(path) as data_file: return patient.Patient(json.load(data_file))
def individual_to_fhir(obj): """Converts Individual to FHIR Patient. :param obj: Individual json :return: FHIR Patient json """ # first validate if phenopackets object is well-formed schema_path = os.path.join(SCHEMA_PATH, 'individual_schema.json') try: validate_schema(schema_path, obj) except jsonschema.exceptions.ValidationError: raise Exception("The individual object is not valid.") patient = p.Patient() patient.id = obj['id'] patient.birthDate = fhirdate.FHIRDate(obj.get('dateOfBirth', None)) patient.gender = obj.get('sex', None) patient.active = obj.get('active', None) patient.deceasedBoolean = obj.get('deceased', None) patient.extension = list() # age if 'age' in obj: age_extension = age_to_fhir( obj, PHENOPACKETS_ON_FHIR_MAPPING['individual']['age'], 'age') patient.extension.append(age_extension) # karyotypic_sex if 'karyotypicSex' in obj: karyotypic_sex_extension = extension.Extension() karyotypic_sex_extension.url = PHENOPACKETS_ON_FHIR_MAPPING[ 'individual']['karyotypicSex']['url'] karyotypic_sex_extension.valueCodeableConcept = codeableconcept.CodeableConcept( ) karyotypic_sex_extension.valueCodeableConcept.coding = list() coding = c.Coding() coding.display = obj.get('karyotypicSex', None) coding.code = obj.get('karyotypicSex', None) coding.system = PHENOPACKETS_ON_FHIR_MAPPING['individual'][ 'karyotypicSex']['system'] karyotypic_sex_extension.valueCodeableConcept.coding.append(coding) patient.extension.append(karyotypic_sex_extension) # taxonomy if 'taxonomy' in obj: taxonomy_extension = extension.Extension() taxonomy_extension.url = PHENOPACKETS_ON_FHIR_MAPPING['individual'][ 'taxonomy'] taxonomy_extension.valueCodeableConcept = codeableconcept.CodeableConcept( ) taxonomy_extension.valueCodeableConcept.coding = list() coding = c.Coding() coding.display = obj.get('taxonomy', None).get('label', None) coding.code = obj.get('taxonomy', None).get('id', None) taxonomy_extension.valueCodeableConcept.coding.append(coding) patient.extension.append(taxonomy_extension) return patient.as_json()
def import_patient(self, res, options): """Import a single patient""" verbosity = options['verbosity'] strict = options['strict'] force = options['force'] f_patient = pat.Patient(res, strict=strict) # OC: Normal logging for progress. Do not write to stdout or stderr as some sample code for manage commands does. logger.info(f'Importing {f_patient}') official_name = [x for x in f_patient.name if x.use == 'official'][0] # pylint: disable=E1133 # TODO: Pull type code from settings primary_identifier = [ x for x in f_patient.identifier if self.hastypecode(x, 'MR') ][0] # pylint: disable=E1133 d_patient = Patient(id=f_patient.id, identifier=primary_identifier.value, name=self.get_humanname(official_name), gender=f_patient.gender, birth_date=f_patient.birthDate.isostring) # TODO: This is currently not working as it should. Problems with updating existing entries and created_at NOT NULL constraints # Do I need to .create() the object first, before saving it??? try: d_patient.full_clean(validate_unique=False) except ValidationError as err: # OC: Error logging with exceptions will also be sent to telemetry logger.error('Validation failed', exc_info=True) try: d_patient.save() except IntegrityError as err: logger.error('Saving to database failed', exc_info=True) # TODO: This should use bulk_create for f_patid in f_patient.identifier: d_patid = PatientIdentifier(type_code=self.get_codeableconcept( f_patid.type), system=f_patid.system, value=f_patid.value, subject_id=f_patient.id) try: d_patid.save() except IntegrityError as err: logger.error('Saving patient identifier to database failed', exc_info=True)
def mkpatient(): """ make a Patient resource using the data model """ import fhirclient.models.patient as p import fhirclient.models.humanname as hn patient = p.Patient() # patient.id = 'patient-1' # print(patient.id) # prints `patient-1` name = hn.HumanName() name.given = ['Peter'] name.family = 'Parker' patient.name = [name] # print(json.dumps(patient.as_json(), indent=4)) patient.uuid = uuid.uuid4().urn print(patient.uuid) return (patient)
def to_fhir_obj(self): patient = p.Patient() identifier = p.identifier.Identifier() identifier.value = self.id patient.identifier = [identifier] name = hn.HumanName() name.given = [self.first_name] name.family = self.last_name patient.name = [name] patient.gender = self.sex patient.birthDate = fd.FHIRDate(str(datetime.utcnow().date())) # prints patient's JSON representation, now with id and name address = a.Address() address.state = self.state address.district = self.district patient.address = [address] json = patient.as_json() return patient
def fhir_patient(obj): """ Converts Individual to FHIR Patient. """ patient = p.Patient() patient.id = obj['id'] patient.birthDate = fhirdate.FHIRDate(obj.get('date_of_birth', None)) patient.gender = obj.get('sex', None) patient.active = obj.get('active', None) patient.deceasedBoolean = obj.get('deceased', None) patient.extension = list() # age if 'age' in obj.keys(): age_extension = fhir_age( obj, PHENOPACKETS_ON_FHIR_MAPPING['individual']['age'], 'age') patient.extension.append(age_extension) # karyotypic_sex karyotypic_sex_extension = extension.Extension() karyotypic_sex_extension.url = PHENOPACKETS_ON_FHIR_MAPPING['individual'][ 'karyotypic_sex']['url'] karyotypic_sex_extension.valueCodeableConcept = codeableconcept.CodeableConcept( ) karyotypic_sex_extension.valueCodeableConcept.coding = list() coding = c.Coding() coding.display = obj.get('karyotypic_sex', None) coding.code = obj.get('karyotypic_sex', None) coding.system = PHENOPACKETS_ON_FHIR_MAPPING['individual'][ 'karyotypic_sex']['system'] karyotypic_sex_extension.valueCodeableConcept.coding.append(coding) patient.extension.append(karyotypic_sex_extension) # taxonomy if 'taxonomy' in obj.keys(): taxonomy_extension = extension.Extension() taxonomy_extension.url = PHENOPACKETS_ON_FHIR_MAPPING['individual'][ 'taxonomy'] taxonomy_extension.valueCodeableConcept = codeableconcept.CodeableConcept( ) taxonomy_extension.valueCodeableConcept.coding = list() coding = c.Coding() coding.display = obj.get('taxonomy', None).get('label', None) coding.code = obj.get('taxonomy', None).get('id', None) taxonomy_extension.valueCodeableConcept.coding.append(coding) patient.extension.append(taxonomy_extension) return patient.as_json()
def PatientCreate(client): print("PatCreate") jsondict = { "resourceType": "Patient", "text": { "status": "generated", "div": "<div xmlns=\"http://www.w3.org/1999/xhtml\">Ryan</div>" }, "active": True, "name": [{ "use": "official", "family": "Murky", "given": ["Ryan"] }], "gender": "male", "birthDate": "1974-12-25", "deceasedBoolean": False } return P.Patient(jsondict, strict=False).create(client.server)
from fhirclient import client settings = {'app_id': 'test_app', 'api_base': 'http://test.fhir.org/r4/'} ## REMOVE ID FIELD gen_json = { "resourceType": "Patient", "name": [{ "use": "official", "given": ["Peter"], "family": "Man" }], "gender": "male" } smart = client.FHIRClient(settings=settings) import fhirclient.models.patient as p patient_gen = p.Patient(gen_json) #Change gender to female patient_gen.gender = "female" print("Preview resource as JSON\n") print(patient_gen.as_json()) print("\n") print("Return from FHIR test server\n") pt1_created = patient_gen.create(smart.server) print(pt1_created)
def read_patient(data: dict) -> patient.Patient: return patient.Patient(data, False)
def _generate_patient_fhir_object(self): """Creates a test patient using fhirclient.models.""" Patient = p.Patient() HumanName = hn.HumanName() HumanName.family = [self.name_last] HumanName.given = [self.name_first] Patient.name = [HumanName] Patient.gender = self.gender birthDay = fd.FHIRDate() birthDay.date = self.bday Patient.birthDate = birthDay Address = a.Address() Address.country = 'USA' Address.postalCode = self.zipcode Address.state = self.state Address.city = self.city Address.line = [f'{self.address_number} {self.address_street}'] Address.use = 'home' Address.type = 'postal' Patient.active = True Patient.address = [Address] PatientCommunication = p.PatientCommunication() PatientCommunication.language = self._create_FHIRCodeableConcept( 'en-US', 'urn:ietf:bcp:47', 'English') # PatientCommunication.language = self._create_FHIRCodeableConcept('en-US','http://hl7.org/fhir/ValueSet/languages','English') PatientCommunication.preferred = True Patient.communication = [PatientCommunication] race = e.Extension() race.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-race' us_core = e.Extension() us_core.url = 'ombCategory' us_core.valueCoding = self._create_FHIRCoding( self.race_code, 'urn:oid:2.16.840.1.113883.6.238', self.race_description) race_detailed = e.Extension() race_detailed.url = 'detailed' race_detailed.valueCoding = self._create_FHIRCoding( self.race_code, 'urn:oid:2.16.840.1.113883.6.238', self.race_description) race_text = e.Extension() race_text.url = 'text' race_text.valueString = self.race_description race.extension = [us_core, race_detailed, race_text] ethnicity = e.Extension() ethnicity.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity' us_core = e.Extension() us_core.url = 'ombCategory' us_core.valueCoding = self._create_FHIRCoding( self.ethnicity_code, 'urn:oid:2.16.840.1.113883.6.238', self.ethnicity_description) ethnicity_text = e.Extension() ethnicity_text.url = 'text' ethnicity_text.valueString = self.ethnicity_description ethnicity.extension = [us_core, ethnicity_text] Patient.extension = [race, ethnicity] Patient.managingOrganization = self._create_FHIRReference( self.Organization) self._validate(Patient) self.response = self.post_resource(Patient) Patient.id = self._extract_id() self.Patient = Patient print(self)
df_a['date_of_birth'] = pd.to_datetime(df_a['date_of_birth'], errors='coerce') # now back into str or fhirdate will complain df_a['date_of_birth'] = df_a['date_of_birth'].apply( lambda x: x.strftime('%Y-%m-%d') if not pd.isnull(x) else '') print(df_a.head()) # In[6]: # default server/path server = "https://localhost:3000/Patient" # 3 records, modify if more are required limit = 100 for index, row in itertools.islice(df_a.iterrows(), limit): # for index, row in df_a.iterrows(): patient = p.Patient() # not using rec_id as pandas id, leaving empty patient.gender = row['sex'] name = hn.HumanName() name.given = [row['given_name']] name.family = row['surname'] name.use = 'official' patient.name = [name] phone = cp.ContactPoint() phone.system = 'phone' phone.value = row['phone_number'] patient.telecom = [phone] patient.birthDate = fd.FHIRDate(row['date_of_birth']) emr = ident.Identifier() emr.system = 'http://clientregistry.org/openmrs' emr.value = row['rec_id'] art = ident.Identifier()
message= 'Program can\'t run without a server URL. Are you sure you want to continue?' ) if warning: flag = False exit() else: flag = False else: flag = False # Post example patient and get ID with open('Patient-example.json', 'r') as f: data = json.load(f) fhir_pat = patient.Patient(data) low_val_col = 'Einheit_Wert_min' high_val_col = 'Einheit_Wert_max' numerical_cols = [low_val_col, high_val_col] col_names = ['ASK_Substanz_allg'] coding_col_names = [ 'UNII_Substanz_allg', 'ASK_Substanz_allg', 'CAS_Substanz_allg' ] coding_display_col = 'Substanz_allg_engl_INN_oder_sonst' route_code_col = 'Routes and Methods of Administration - Concept Code' route_display_col = 'Routes and Methods of Administration - Term' ops_text_col = 'opsText' unit_code_col = 'UCUM-Code' unit_col = 'UCUM-Description' ops_code_col = 'opsCode'
import fhirclient.models.patient as patient_model import json if __name__ == '__main__': patient_json = json.load(open('patient.json')) patient = patient_model.Patient(patient_json)
def get_dashboard_FHIR_current_data(): settings = { 'app_id': 'LGBTQCovidReporting', 'api_base': 'https://r4.smarthealthit.org' } smart = client.FHIRClient(settings=settings) covid_historic_county_data_url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv' lgbt_population_data_url = 'https://raw.githubusercontent.com/PatrickGood/lgbt-covid-data/main/lgbt_populations.csv' state_abbr_data_url = 'https://raw.githubusercontent.com/PatrickGood/lgbt-covid-data/main/state_abbreviations.csv' covid_historic_county_data = pd.read_csv(covid_historic_county_data_url, dtype={"fips": str}) yesterday_date = str((pd.datetime.utcnow() - timedelta(2)).date()) # latest_covid_historic_county_data = covid_historic_county_data[covid_historic_county_data['date'] == yesterday_date] lgbt_population_data = pd.read_csv(lgbt_population_data_url, thousands=',')[["STATE", "LGBT POPULATION DENSITY"]] state_abbreviations = pd.read_csv(state_abbr_data_url) covid_historic_county_data['state_lower'] = covid_historic_county_data['state'].str.lower() lgbt_population_data['state_lower'] = lgbt_population_data['STATE'].str.lower() lgbt_covid_data_history = pd.merge(covid_historic_county_data, lgbt_population_data, how='inner', on='state_lower') lgbt_covid_data_history['lgbt_cases'] = lgbt_covid_data_history['cases'] * lgbt_covid_data_history[ 'LGBT POPULATION DENSITY'] // 100 lgbt_covid_data_history['lgbt_deaths'] = lgbt_covid_data_history['deaths'] * lgbt_covid_data_history[ 'LGBT POPULATION DENSITY'] // 100 lgbt_covid_data_history.dropna(inplace=True) lgbt_covid_data_history = lgbt_covid_data_history.astype(({'lgbt_cases': 'int32', 'lgbt_deaths': 'int32'})) lgbt_covid_data_history = pd.merge(lgbt_covid_data_history, state_abbreviations, how="inner", on='state') current_columns = ['state', 'county', 'abbreviation', 'fips', 'cases', 'lgbt_cases', 'deaths', 'lgbt_deaths', 'LGBT POPULATION DENSITY'] final_lgbt_covid_data_current = lgbt_covid_data_history[lgbt_covid_data_history['date'] == yesterday_date] final_lgbt_covid_data_current = final_lgbt_covid_data_current[current_columns].sort_values(by=['fips']) final_current_columns = ['state', 'county', 'abbreviation', 'fips', 'lgbt_cases', 'cases'] final_lgbt_covid_data_current = final_lgbt_covid_data_current[final_current_columns].sort_values(by=['fips']) fip_list =[] fip_data_url="https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json" # python 3.x r = requests.get(fip_data_url) for item in r.json()['features']: item_properties = item['properties'] fip_list.append([item['id'], item_properties['STATE'], item_properties['COUNTY'], item_properties['NAME']]) fip_data_pd = pd.DataFrame(fip_list, columns=['id', 'state_id', 'county_id', 'county']) fips_state_data_url = 'https://raw.githubusercontent.com/PatrickGood/lgbt-covid-data/main/fips_state.csv' fips_state_data_df = pd.read_csv(fips_state_data_url, dtype={"fips_code": str}, error_bad_lines=False) fips_df = pd.merge(fip_data_pd, fips_state_data_df, 'inner', left_on='state_id', right_on='fips_code') fips_df['lookup_key'] = fips_df['state'] + fips_df['county'] query_url ='/Patient?_has:Condition:patient:code=http://snomed.info/sct|840539006&_has:Condition:patient:verification-status=http://terminology.hl7.org/CodeSystem/condition-ver-status|confirmed&_has:Observation:patient:code=http://loinc.org|76690-7&_has:Observation:patient:value-string=Other,Homosexual,Bisexual&_count=250' result = smart.server.request_json(query_url) fhir_positive_lgbt_cases_df = pd.DataFrame(columns=['key', 'count']) fhir_positive_lgbt_cases_lst = [] #p.Patient(smart.server.request_json(bundle_url_next)['entry'][000]['resource']) if result is not None and 'entry' in result.keys(): for entry in result['entry']: if entry['resource']['resourceType'] == 'Patient': patient = p.Patient(entry['resource']) state = None district = None if patient.address is not None and len(patient.address) > 0: address = patient.address[0] if address.state: state = address.state if address.district: district = address.district key = state + district fhir_positive_lgbt_cases_lst.append([key, 1]) while(any(obj['relation'] == 'next' for obj in result['link']) and len(fhir_positive_lgbt_cases_lst) < 1000): query_url = result['link'][-1]['url'] result = smart.server.request_json(query_url) if result is not None and 'entry' in result.keys(): for entry in result['entry']: if entry['resource']['resourceType'] == 'Patient': patient = p.Patient(entry['resource']) state = None district = None if patient.address is not None and len(patient.address) > 0: address = patient.address[0] if address.state: state = address.state if address.district: district = address.district key = state + district fhir_positive_lgbt_cases_lst.append([key, 1]) fhir_positive_lgbt_cases_df = pd.DataFrame(fhir_positive_lgbt_cases_lst, columns=['key', 'count']) fhir_positive_lgbt_cases_fips_df = pd.merge(fhir_positive_lgbt_cases_df, fips_df, how='inner', left_on='key', right_on='lookup_key') final_stats = fhir_positive_lgbt_cases_fips_df.groupby('id')['count'].sum() final_stats_states = pd.merge(final_stats, fips_df, how='inner', on='id') final_stats_states = final_stats_states[['id', 'count', 'fips_code', 'post_code', 'lookup_key']] final_stats_states_population = pd.merge(final_stats_states, final_lgbt_covid_data_current, how='inner', left_on='id', right_on='fips') final_data_frame = final_stats_states_population[ ['fips', 'state', 'county', 'post_code', 'count', 'cases', 'lgbt_cases']] return final_data_frame else: return pd.DataFrame(columns=[['fips', 'state', 'county', 'post_code', 'count', 'cases', 'lgbt_cases']])
def patient(): user = get_jwt_identity() print("user:"******"name_given"]] name.family = request.form["name_family"] patient.name = [name] # 设置性别 只能是male或者female patient.gender = request.form["gender"] if request.form[ "gender"] == "男" or request.form["女"] == "female" else "" # 设置生日 patient.birthDate = fdate.FHIRDate().with_json( request.form["birthDate"]) # 设置逻辑删除 patient.active = True # 设置地址 patient.address = [ad.Address({"city": request.form["city"]})] ret = mongodb.basic_information.insert_one(patient.as_json()) print(ret) return ret_data(200, '请求成功', 1003) else: return ret_data(200, "请求成功", 2008) elif request.method == 'GET': dict01 = mongodb.basic_information.find_one({ 'id': str(user), 'active': True }) if dict01 is None: return ret_data(200, '请求成功', 2011) dict02 = {} del dict01['_id'] dict02['city'] = dict01['address'][0]['city'] dict02['birthDate'] = dict01['birthDate'] dict02['gender'] = dict01['gender'] dict02['name'] = str(dict01['name'][0]['family']) + str( dict01['name'][0]['given'][0]) return ret_data(200, '请求成功', 1005, **dict02) elif request.method == 'DELETE': count = 0 for i in patientList: print(i['active']) if i['active'] is True: count += 1 if count >= 1: mongodb.basic_information.update_one( { 'id': str(user), 'active': True }, {'$set': { 'active': False }}) # mongodb.basic_information.delete_one({'id':str(user)}) return ret_data(200, '请求成功', 1004) else: return ret_data(200, '请求成功', 2010) elif request.method == 'PUT': count = 0 for i in patientList: print(i['active']) if i['active'] is True: count += 1 if count == 1: patient = p.Patient({'id': str(user)}) # 设置名字 name = hn.HumanName() name.given = [request.form["name_given"]] name.family = request.form["name_family"] patient.name = [name] # 设置性别 只能是male或者female patient.gender = request.form["gender"] if request.form[ "gender"] == "男" or request.form["女"] == "female" else "" # 设置生日 patient.birthDate = fdate.FHIRDate().with_json( request.form["birthDate"]) # 设置逻辑删除 patient.active = True # 设置地址 patient.address = [ad.Address({"city": request.form["city"]})] mongodb.basic_information.update_one({'id': str(user)}, {'$set': patient.as_json()}) return ret_data(200, '请求成功', 1006) else: return ret_data(200, '请求成功', 2009) return ret_data(200, '请求成功', 1000, test='hello world')
# Make an authenticated API request session = get_session() headers = {"Content-Type": "application/fhir+json;charset=utf-8"} patient = p.Patient({'id': 'patient-1'}) # body = { # "name": [{"use": "official", "family": "Smith", "given": ["Darcy"]}], # "gender": "female", # "birthDate": "1970-01-01", # "resourceType": "Patient", # } body = patient.as_json() response = session.post(fhir_store_path, headers=headers, json=body) response.raise_for_status() resource = response.json() print("Created Patient resource with ID {}".format(resource["id"])) return response patient = p.Patient({'id': 'patient-1'}) print(patient.as_json()) create_patient(_BASE_URL, PROJECT_ID, CLOUD_REGION, DATASET_ID, FHIR_STORE)
from fhirclient import client settings = {'app_id': 'test_app', 'api_base': 'http://test.fhir.org/r4/'} smart = client.FHIRClient(settings=settings) import fhirclient.models.patient as p import fhirclient.models.humanname as hn import fhirclient.models.contactpoint as cp patient1 = p.Patient() contact = cp.ContactPoint() contact.system = 'phone' contact.value = '00999811119' patient1.telecom = [contact] name = hn.HumanName() name.given = ['Peter2'] name.family = 'Man' patient1.name = [name] patient1.gender = 'male' #This won't show as it's not part of the FHIR spec patient1.gender2 = 'male' print("Preview resource as JSON\n") print(patient1.as_json()) print("\n") print("Return from FHIR test server\n") pt1_created = patient1.create(smart.server)
def createPatient(dohmpifield, record): #extract fields from dohmpi from database field = [] for i in range(len(dohmpifield)): f1, = dohmpifield[i] # dohmpi loads from db as a list of onetuples. field.append(f1) # we make a traditional list to refer to. fnamei = field.index('provider_first') lnamei = field.index('provider_last') genderi = field.index('provider_gender_cd') deathyi = field.index('deathccyy') deathmi = field.index('deathmm') deathdi = field.index('deathdd') birthi = field.index('provider_dob_dob') provi = field.index('provider_license_no') # record is one record from the postgres db import fhirclient.models.patient as p # set patient id as provider licence numberS pid = record[provi] p = p.Patient({}) import fhirclient.models.identifier as idf identifier = idf.Identifier() identifier.value = pid p.identifier = [identifier] # resolve name import fhirclient.models.humanname as hn name = hn.HumanName() name.given = [record[fnamei]] name.family = [record[lnamei]] p.name = [name] #[name.family, name.given] # resolve gender if (record[genderi] == "1"): p.gender = 'male' elif (record[genderi] == "2"): p.gender = 'female' else: p.gender = 'unknown' # build and resolve birthdate birthdate = record[birthi] bsep1 = birthdate.index("/") bsep2 = birthdate.index("/", bsep1 + 1) year = birthdate[-4:] month = birthdate[0:bsep1] if (len(month) < 2): month = "0%s" % month date = birthdate[bsep1 + 1:bsep2] if (len(date) < 2): date = "0%s" % date birthdate = year + "-" + month + "-" + date p.birthDate = fhirclient.models.fhirdate.FHIRDate(birthdate) # build and resolve death date tt = "12:00:00" #Setting time to noon yyyy = record[deathyi] mm = record[deathmi] if (len(mm) < 2): mm = "0%s" % mm dd = record[deathdi] if (len(dd) < 2): dd = "0%s" % dd deathdate = "%s-%s-%sT%s" % (yyyy, mm, dd, tt) deathdate = fhirclient.models.fhirdate.FHIRDate(deathdate) # Create period import fhirclient.models.period as per per = per.Period() per.start = deathdate p.deceasedBoolean = True p.deceasedDateTime = deathdate return p
def postPatient(name): pat = p.Patient({"name": [{"use": name}]}) result = p.Patient.create( pat, smart.server)['issue'][0]['diagnostics'].split('/')[1] return result
def create_fhir_object(self): """ Generate a fhirclient.Patient class object and store in the protected attribute _fhir :return: None """ # Patient object must be persistent to generate FHIR attributes ins = inspect(self) if ins.persistent: # Initialize Patient resource fhir_pt = fhir_patient.Patient() # Set resource logical identifier fhir_pt.id = self.get_url() # Build and assign Meta resource for Patient object fhir_meta = meta.Meta() fhir_meta.lastUpdated = fhir_gen_datetime(value=self.updated_at, error_out=False, to_date=False) fhir_meta.versionId = str(self.version_number) fhir_meta.profile = ['http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient'] fhir_pt.meta = fhir_meta # Patient name represented as HumanName resource fhir_pt.name = [] fhir_pt.name.append(fhir_gen_humanname(use='usual', first_name=self.first_name, last_name=self.last_name, middle_name=self.middle_name, suffix=self.suffix, prefix=self.prefix)) # Display MRN as identifier codeable concept = Patient.identifier.codeableconcept.coding # Initialize Identifier resource id_mrn = identifier.Identifier() id_mrn.use = 'usual' id_mrn.system = 'http://unkani.com' id_mrn.value = str(self.uuid) # Initialize CodeableConcept resource mrn_cc = codeableconcept.CodeableConcept() mrn_cc.text = 'Medical Record Number' # Initialize Coding resource mrn_coding = coding.Coding() mrn_coding.system = 'http://hl7.org/fhir/v2/0203' mrn_coding.code = 'MR' mrn_coding.display = 'Medical Record Number' # Assign Coding resource to CodeableConcept mrn_cc.coding = [mrn_coding] # Assign CodeableConcept to Identifier id_mrn.type = mrn_cc # Assign CodeableConcept to Patient fhir_pt.identifier = [id_mrn] # Display SSN as identifier codeable concept = Patient.identifier.codeableconcept.coding if self.ssn: # Initialize Identifier resource id_ssn = identifier.Identifier() id_ssn.use = 'usual' id_ssn.system = 'http://hl7.org/fhir/sid/us-ssn' id_ssn.value = self.ssn # Initialize CodeableConcept resource ssn_cc = codeableconcept.CodeableConcept() ssn_cc.text = 'Social Security Number' # Initialize Coding resource ssn_coding = coding.Coding() ssn_coding.system = 'http://hl7.org/fhir/v2/0203' ssn_coding.code = 'SS' ssn_coding.display = 'Social Security Number' # Assign Coding resource to CodeableConcept ssn_cc.coding = [ssn_coding] # Assign CodeableConcept to Identifier id_ssn.type = ssn_cc # Assign CodeableConcept to Patient fhir_pt.identifier.append(id_ssn) if self.marital_status: marital_status_cc = codeableconcept.CodeableConcept() marital_status_url = 'http://hl7.org/fhir/ValueSet/marital-status' marital_status_concept = ValueSet.get_valueset_concept(marital_status_url, self.marital_status) if marital_status_concept: marital_status_cc.text = getattr(marital_status_concept, 'display') marital_status_coding = coding.Coding() marital_status_coding.code = self.marital_status marital_status_coding.system = marital_status_url marital_status_coding.display = marital_status_cc.text marital_status_cc.coding = [marital_status_coding] fhir_pt.maritalStatus = marital_status_cc if self.race: ext_race = extension.Extension() ext_race.url = 'http://hl7.org/fhir/StructureDefinition/us-core-race' race_url = 'http://hl7.org/fhir/us/core/ValueSet/omb-race-category' cc_race = codeableconcept.CodeableConcept() race_concept = ValueSet.get_valueset_concept(race_url, self.race) if race_concept: cc_race.text = getattr(race_concept, 'display') coding_race = coding.Coding() coding_race.system = race_url coding_race.code = self.race coding_race.display = cc_race.text cc_race.coding = [coding_race] ext_race.valueCodeableConcept = cc_race try: fhir_pt.extension.append(ext_race) except AttributeError: fhir_pt.extension = [ext_race] if self.ethnicity: ext_ethnicity = extension.Extension() ext_ethnicity.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity' cc_ethnicity = codeableconcept.CodeableConcept() cc_ethnicity.text = ethnicity_dict.get(self.ethnicity)[0].capitalize() coding_ethnicity = coding.Coding() coding_ethnicity.system = 'http://hl7.org/fhir/us/core/ValueSet/omb-ethnicity-category' coding_ethnicity.code = self.race coding_ethnicity.display = cc_ethnicity.text cc_ethnicity.coding = [coding_ethnicity] ext_ethnicity.valueCodeableConcept = cc_ethnicity try: fhir_pt.extension.append(ext_ethnicity) except AttributeError: fhir_pt.extension = [ext_ethnicity] if self.sex: sex_dict = {"administrativeGender": {"M": "male", "F": "female", "u": "unknown", "o": "other"}, "usCoreBirthSex": {"M": "M", "F": "F", "U": "UNK", "O": "UNK"}} fhir_pt.gender = sex_dict['administrativeGender'][str(self.sex).upper()] ext_birth_sex = extension.Extension() ext_birth_sex.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-birthsex' ext_birth_sex.valueCode = sex_dict['usCoreBirthSex'][str(self.sex).upper()] try: fhir_pt.extension.append(ext_birth_sex) except AttributeError: fhir_pt.extension = [ext_birth_sex] if self.dob: fhir_pt.birthDate = fhir_gen_datetime(value=self.dob, to_date=True) fhir_pt.active = self.active fhir_pt.deceasedBoolean = self.deceased if self.deceased_date: fhir_pt.deceasedDateTime = fhir_gen_datetime(value=self.deceased_date, to_date=False) if self.preferred_language: fhir_comm = fhir_patient.PatientCommunication() fhir_comm.preferred = True fhir_lang_cc = codeableconcept.CodeableConcept() fhir_lang_coding = coding.Coding() fhir_lang_coding.code = self.preferred_language fhir_lang_url = 'http://hl7.org/fhir/ValueSet/languages' fhir_lang_coding.system = fhir_lang_url fhir_lang_concept = ValueSet.get_valueset_concept(fhir_lang_url, self.preferred_language) if fhir_lang_concept: fhir_lang_coding.display = fhir_lang_concept.display fhir_lang_cc.text = fhir_lang_coding.display fhir_lang_cc.coding = [fhir_lang_coding] fhir_comm.language = fhir_lang_cc fhir_pt.communication = [fhir_comm] contact_point_list = [] phone_list = self.phone_numbers.all() if phone_list: for ph in phone_list: contact_point_list.append(ph.fhir) email_list = self.email_addresses.all() if email_list: for em in email_list: contact_point_list.append(em.fhir) if contact_point_list: fhir_pt.telecom = contact_point_list address_list = self.addresses.all() if address_list: fhir_pt.address = [] for addr in address_list: fhir_pt.address.append(addr.fhir) xhtml = render_template('fhir/patient.html', fhir_patient=fhir_pt, patient=self) fhir_pt.text = narrative.Narrative() fhir_pt.text.status = 'generated' fhir_pt.text.div = xhtml self._fhir = fhir_pt