def get_smart(self): state = self.request.session.get('state') if state: return client.FHIRClient(state=state, save_func=self.save_state) else: return client.FHIRClient(settings=smart_defaults, save_func=self.save_state)
def _get_smart(): state = session.get('state') if state: return client.FHIRClient(state=state, save_func=_save_state) else: return client.FHIRClient(settings=smart_defaults, save_func=_save_state)
def _get_epic(): state = session.get('epic_state') if state: return client.FHIRClient(state=state, save_func=_save_epic_state) else: return client.FHIRClient(settings=epic_defaults, save_func=_save_epic_state)
def launch(request): iss = request.GET.get('iss') if iss: _ENDPOINT.update({ 'api_base': iss, 'auth_type': 'oauth2', 'patient_id': None, 'launch_token': request.GET.get('launch'), 'redirect_uri': _ENDPOINT['app_base'] + "authorize.html" }) smart = client.FHIRClient(settings=_ENDPOINT) auth_url = smart.authorize_url request.session['client_state'] = smart.state # TO DO: encrypt the state to protect app secrets return redirect(auth_url) fhirServiceUrl = request.GET.get('fhirServiceUrl') if fhirServiceUrl: _ENDPOINT['api_base'] = fhirServiceUrl _ENDPOINT['patient_id'] = request.GET.get('patientId') _ENDPOINT['auth_type'] = 'none' smart = client.FHIRClient(settings=_ENDPOINT) redirect_url = _ENDPOINT['app_base'] + "index.html" request.session['client_state'] = smart.state # TO DO: encrypt the state to protect app secrets return redirect(redirect_url)
def _get_smart(new_settings={}): state = session.get('state') settings = smart_defaults #the global defaults settings.update(new_settings) #specific overriding defaults if state: return client.FHIRClient(state=state, save_func=_save_state) else: return client.FHIRClient(settings=smart_defaults, save_func=_save_state)
def __init__(self, request): self.request = request state = self.request.session.get('state') if state: self.smart = client.FHIRClient(state=state, save_func=self.save_state) print('state is: {0}'.format(state)) else: self.smart = client.FHIRClient(settings=self.smart_defaults, save_func=self.save_state) print('no state, create new connection')
def patient(id): helloval = request.args.get('hello') output = "<p>" smart = client.FHIRClient(settings=settings) smart.prepare() smart = client.FHIRClient(settings=settings) import fhirclient.models.patient as p try: import fhirclient.models.patient as p patient = p.Patient.read(id, smart.server) output = "<h2>" + id + "</h2><p>" + patient.name[0].given[ 0] + " " + patient.name[0].family + "</p>" except: output = "Cannot find a patient based on the ID provided." return output
def get_patient_info(patient_id): settings = { 'app_id': 'LGBTQCovidReporting', 'api_base': 'https://r4.smarthealthit.org' } smart = client.FHIRClient(settings=settings) patient = p.Patient.read(patient_id, smart.server) patient_name = get_patient_name(patient) patient_address = get_patient_address(patient) patient_birthdate = str(patient.birthDate.date) patient_gender = patient.gender tested_positive = False bundle = p.Patient.where({'_id': str(patient_id), '_has:Condition:patient:code':'http://snomed.info/sct|840539006', '_has:Condition:patient:verification-status':'http://terminology.hl7.org/CodeSystem/condition-ver-status|confirmed'}, ).perform(smart.server) if bundle.entry: if len(bundle.entry) > 0: tested_positive = True sexuality = "I choose not to answer" bundle = o.Observation.where({'subject': str(patient_id), 'code':'http://loinc.org|76690-7', '_sort':'-date', '_count':'1'} ).perform(smart.server) if bundle.entry: if len(bundle.entry) > 0: sexuality = bundle.entry[0].resource.valueString return [patient_id, patient_name, patient_gender, patient_birthdate, patient_address, tested_positive, sexuality]
def form(): if request.method == 'GET': return ''' <form method="post"> Search for a Name: <input type="text" name="text1" /> <input type="submit" name="Search" value="Search" /> </form> ''' else: # return 'You entered:'+request.form.get('text1'); smart = client.FHIRClient(settings=settings) smart.prepare() import fhirclient.models.patient as p search = p.Patient.where({'name': request.form.get('text1')}) patients = search.perform_resources(smart.server) serializablepatientarray = [] output = "<table>" for patient in patients: output = output + "<tr>" output = output + "<td><a href='/patient/" + patient.id + "'>" + patient.name[ 0].given[0] + "</a></td>" output = output + "<td><a href='/patient/" + patient.id + "'>" + patient.name[ 0].family + "</a></td>" output = output + "</tr>" output = output + "</table>" return render_template('search.html', output=Markup(output))
def __init__(self, questionnaire_id, *args, **kwargs): super(FHIRQuestionnaireForm, self).__init__(*args, **kwargs) try: # Prepare the client fhir = client.FHIRClient(settings={'app_id': settings.FHIR_APP_ID, 'api_base': settings.FHIR_URL}) # Get the questionnaire questionnaire = Questionnaire.read(questionnaire_id, fhir.server) # Retain it self.questionnaire_id = questionnaire_id self.questionnaire = questionnaire except FHIRNotFoundException: raise FHIR.QuestionnaireDoesNotExist # Get fields self.fields = self._get_form_fields(questionnaire, questionnaire_id) self.fields['questionnaire_id'] = forms.CharField(empty_value=questionnaire_id, widget=forms.HiddenInput) # Create the crispy helper self.helper = FormHelper(self) self.helper.form_method = 'POST' # Set the layout self.helper.layout = self._get_form_layout(self.questionnaire.item) # Add a submit button self.helper.layout.append(ButtonHolder(Submit('submit', 'Submit', css_class='btn btn-primary')))
def get_patient_info(pat_id): """ Queries a FHIR server for patient information Args: param1: FHIR patient ID Returns: A dictionary that includes a patient's name, ID, date of birth, age, and gender """ smart = client.FHIRClient(settings=SETTINGS) import fhirclient.models.patient as p patient = p.Patient.read(pat_id, smart.server) name = patient.name[0].given[0] + ' ' + patient.name[0].family dob = patient.birthDate.isostring #yyyy-mm-dd age = calculate_age(patient.birthDate.date) gender = patient.gender return { 'name': name, 'id': pat_id, 'dob': dob, 'age': age, 'gender': gender }
def get_procedure_info(proc_id): """ Queries a FHIR server for procedure information. The procedure text might be in a TIU database, so it's currently just part of the template. Args: param1: FHIR procedure ID Returns: A dictionary that includes the procedure ID, exam type (name), indications, and an array of associated diagnostic codes/descriptions. The array type works well with JS and Python. """ smart = client.FHIRClient(settings=SETTINGS) import fhirclient.models.procedure as p proc = p.Procedure.read(proc_id, smart.server) exam_type = proc.code.coding[0].display indications = proc.reasonCode[0].text cond_code_desc = [] for cond in proc.reasonReference: cond_json = json.loads(urllib.request.urlopen(SETTINGS['api_base'] + '/Condition/' + \ cond.reference.split('/')[1]).read()) cond_code_desc.append([cond_json['code']['coding'][0]["code"], \ cond_json['code']['coding'][0]['display']]) return { 'proc_id': proc_id, 'exam_type': exam_type, 'indications': indications, 'condition': cond_code_desc }
def get_patient_aggregate_data(patient_id='212', window_secs=72000, interval_secs=600, calc_cnt=40): settings = { 'app_id': 'my_web_app', 'api_base': "http://35.192.2.85:8080/baseDstu2/", 'count': '500' } smart = client.FHIRClient(settings=settings) pd = pat_dat(patient_id, smart) pat_ag_dat = {} for obn in pd.observation_list: pat_ag_dat[obn] = np.zeros(0) pat_ag_dat['dt'] = np.zeros(0) end_tm = pd.get_min_max_dts()['max'] for i in range(calc_cnt): start_tm = end_tm - datetime.timedelta(seconds=window_secs) new_vals = pd.get_aggragation_for_dates(start_tm, end_tm) pat_ag_dat['dt'] = np.append(pat_ag_dat['dt'], end_tm) for obn in pd.observation_list: pat_ag_dat[obn] = np.append(pat_ag_dat[obn], new_vals[obn]) end_tm = end_tm - datetime.timedelta(seconds=interval_secs) pat_ag_dat['dt'] = pat_ag_dat['dt'][::-1] for obn in pd.observation_list: pat_ag_dat[obn] = pat_ag_dat[obn][::-1] pat_ag_dat[obn] = ff_and_bf(pat_ag_dat[obn]) return pat_ag_dat
def getPatient(): ''' This method shows how to use the fhirclient's Patient model to get FHIR data from a server. This example returns the ID, name, and birth year for all females over 45 years old. ''' settings = { 'app_id': 'python_FHIR_app', 'api_base': 'http://sqlonfhir-stu3.azurewebsites.net/fhir/' } server = client.FHIRClient(settings=settings).server #Query to FHIR server for all female patients search = p.Patient.where(struct={'gender': 'female'}) results = search.perform_resources(server) count = 0 data = '' #For each female Patient resource returned, extract the birth year to determine age for r in results: try: birthyear = int(r.as_json()['birthDate'].split('-')[0]) if birthyear < 1973: data += r.as_json()['id'] + '\n' + \ r.as_json()['name'][0]['given'][0] + ' ' + r.as_json()['name'][0]['family'] + '\n' + \ 'Born: ' + str(birthyear) + '\n\n' count += 1 except: continue #Return this information to app.py to include in the HTML rendering return 'ID, name, and birth year for each female over 45 years old in the ' + settings['api_base'] + \ ' FHIR server.\n\nTotal: ' + str(count) + '\n\n' + data
def SumAuditType(server, bundle): #include rest summary key = {} smart = client.FHIRClient(settings={'app_id':'audit_app','api_base':server}) while bundle is not None and bundle.entry: for entry in bundle.entry: if not entry.resource.type.code == "rest": if entry.resource.type.code in key: key[entry.resource.type.code] += 1 else: key[entry.resource.type.code] = 1 else: if not "rest" in key: key["rest"] = {} if not entry.resource.subtype: try: key["rest"]['null'] += 1 except KeyError: key["rest"]['null'] = 1 else: for subtype in entry.resource.subtype: if not subtype.code: try: key["rest"]['null'] += 1 except KeyError: key["rest"]['null'] = 1 else: try: key["rest"][subtype.code] += 1 except KeyError: key["rest"][subtype.code] = 1 bundle = NextBundle(smart, bundle) return key
def bootstrap(): settings = { 'app_id': 'my_web_app', 'api_base': "http://35.184.247.92:8080/baseDstu2/", 'count':'500' } smart = client.FHIRClient(settings=settings) # this will run a query that returns all observations search = p.Patient.where ( struct=None) # This will put a bundle into the variable obs with the first 10 results as entries obs = search.perform(smart.server) lastUrl = "" jsonArray = [] lastObject = obs.as_json() # Print it out - while 1 == 1: nex = lastObject lastUrl = nex['link'][1]['url'] r = requests.get(lastUrl) if nex['link'][1]['relation'] == 'previous': break jsonArray.append(r.json()) lastObject = r.json() #print lastUrl nameArray = [] for record in jsonArray: for rec2 in (record['entry']): try: nameArray.append(str(rec2['resource']['name'][0]['use'])) except: pass print str(nameArray) return render_template('bootstrap/startbootstrap-sb-admin-gh-pages/index.html', option_list=nameArray)
def smart(): settings = { "app_id": "integrationtest", "api_base": os.environ["FHIR_SERVER_URL"] } smart = client.FHIRClient(settings=settings) return smart
def setup(): client_instance = client.FHIRClient( settings={ 'app_id': 'epidurio', 'api_base': API_BASES['cerner-open'], } ) return client_instance
def connect(self, **kwargs): """ Connect to the rest api service / data storage. :param kwargs: key based arguments """ self.fhir_client = client.FHIRClient(settings=self.settings) self.fhir_client.prepare() self.server = self.fhir_client.server
def index(request): indexpage = get_template('index.html') # Declare global variables that may be modified here global Global_PATIENT_ID global Global_ADHERE_VARS smart = client.FHIRClient(state=request.session['client_state']) record_change_p = True patientID = smart.patient_id # Get the medication dispenses for this context dispenses = MedicationDispense.where({'patient': patientID}).perform(smart.server) pills = [] if dispenses.entry: for dispense in dispenses.entry: d = dispense.resource name = d.medicationCodeableConcept.coding[0].display assert d.status == 'completed' quant = d.daysSupply.value when = d.whenHandedOver.isostring pills.append((None,name,quant,when)) birthday, patient_name = get_birthday_name(smart) drug = 'all' # We only want to call the adherence_check once for a specific patient if Global_PATIENT_ID == patientID: meds_flags, gaps, refill_data, refill_day = Global_ADHERE_VARS else: tests = adherenceTests.AdherenceTests() meds_flags, gaps, refill_data, refill_day = tests.allTests(pills, drug, birthday) Global_ADHERE_VARS = [meds_flags, gaps, refill_data, refill_day] # save the data for future needs Global_PATIENT_ID = patientID # Medication information will be displayed by drug class. Here we # sort all the patient's medications into drug classes defined # in this application. drug_class_array = {} for n in range(len(meds_flags)): drug_class_array[meds_flags[n][5]] = 1 sorted_drug_class_list = sorted(drug_class_array.keys()) # Send these variables to the page for rendering variables = Context({ 'head_title': u'Medication Adherence Monitor', 'patientID': patientID, 'meds_flags': meds_flags, # Contains all the data needed for tables and plotting 'media_root': settings.MEDIA_ROOT, 'patient_name': patient_name, 'drug_class_array': sorted_drug_class_list, }) output = indexpage.render(variables) response = HttpResponse(output) return response
def getsmart(): """ set setting, and return smart server """ settings = { 'app_id': 'my_web_app', 'api_base': 'http://fhirtest.b12x.org/baseDstu3' } smart = client.FHIRClient(settings=settings) return smart
def update_patients_sexuality(patient_id, sexual_orientation): base_observation = { "resourceType": "Observation", "status": "final", "category": [ { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/observation-category", "code": "social-history", "display": "social-history" } ] } ], "code": { "coding": [ { "system": "http://loinc.org", "code": "76690-7", "display": "Sexual orientation" } ], "text": "Sexual orientation" }, "subject": { "reference": "" }, "performer": [{"reference": ""}], "valueString": "" } settings = { 'app_id': 'LGBTQCovidReporting', 'api_base': 'https://r4.smarthealthit.org' } smart = client.FHIRClient(settings=settings) #id = str(datetime.utcnow().date()) + "pgood7userobservation" + "1" subject_reference = "Patient/" + patient_id #date = datetime.utcnow().isoformat() #sexual_orientations = ['Bisexual', 'Heterosexual', 'Homosexual', 'Other', 'Asked but unknown', 'Unknown'] observation = o.Observation(base_observation) #observation.subject_reference = subject_reference observation.subject.reference = subject_reference observation.performer[0].reference = subject_reference observation.effectiveDateTime = fd.FHIRDate(str(datetime.utcnow().isoformat())) observation.issued = fd.FHIRDate(str(datetime.utcnow().isoformat())) observation.valueString = sexual_orientation new_observation = observation.create(smart.server) if(new_observation): return 200 else: return 400
def demo_fhir_server(): """ Builds a SMART server against Cerner's open playground for querying. See http://fhir.cerner.com/millennium/dstu2/#open-sandbox. Returns: A SMART server that requires no auth tokens to use. """ return client.FHIRClient(settings={ 'app_id': "example", 'api_base': 'https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca' }).server
def fhirclient(self): ''' Make a client. ''' fhirclient = client.FHIRClient({ 'app_id': self.client_id, 'app_secret': self.client_secret, 'api_base': self.fhir_url, 'redirect_uri': self.redirect_uri, 'scope': self.scope, }) return fhirclient
def home_view(request): if not request.user.is_authenticated: return redirect('/') settings = { 'app_id': 'faircare', 'api_base': 'https://launch.smarthealthit.org/v/r3/fhir' } smart = client.FHIRClient(settings=settings) search = med.Medication.where(struct={'_include': '*'}) medications = search.perform_resources(smart.server) for m in medications: m.as_json() # Medication.objects.create(medicine_name=m.code.text) template = loader.get_template('home.html') medication_submit_form = MedicationDataSubmitForm() if request.method == 'POST': medication_submit_form = MedicationDataSubmitForm(request.POST) if medication_submit_form.is_valid(): medication_submit = MedicationPrice( medicine_name=medication_submit_form.cleaned_data.get( 'medication'), price=medication_submit_form.cleaned_data.get( 'medication_price'), state=medication_submit_form.cleaned_data.get( 'medication_state')) messages.success(request, 'Medication Data Submitted Successfully.') medication_submit.save() medication_view_form = MedicationViewForm() medication_view = "" if request.method == 'POST' and 'medication_view' in request.POST: medication_view_form = MedicationViewForm(request.POST) if medication_view_form.is_valid(): medication_view = medication_view_form['medication_view'].value() context = { 'medications': medications, 'medication_submit_form': medication_submit_form, 'medication_view_form': medication_view_form, 'medication_view': medication_view, } return HttpResponse(template.render(context, request))
def test_000_something(self): settings = { 'app_id': 'my_web_app', 'api_base': 'http://fhirtest.b12x.org/r3' } smart = client.FHIRClient(settings=settings) gfefhir = GfeFHIR(smart=smart) self.assertIsInstance(gfefhir, GfeFHIR) gfefhir.annotate('6289') #for ids in ['6227','6228','6229','6234','6235','6236','6241','6242','6243',]: # gfefhir.annotate(ids) # print("--------------") pass
def create_data_if_FHIR_Server_returns_none(): settings = { 'app_id': 'LGBTQCovidReporting', 'api_base': 'https://r4.smarthealthit.org' } smart = client.FHIRClient(settings=settings) bundle = b.Bundle.read_from( '/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', smart.server) if bundle.entry is None or len(bundle.entry) < 1: create_data(smart)
def fhirclient(self): ''' Returns a FHIRClient object from the current state. ''' def save_func(state): # pylint: disable=missing-docstring self._fhirclient = json.dumps(state) if not self._fhirclient: fhirclient = self.provider.fhirclient fhirclient.prepare() state = fhirclient.state else: state = json.loads(self._fhirclient) return client.FHIRClient(state=state, save_func=save_func)
def query(): fhirServer = client.FHIRClient(settings=settings).server #Will print the first names of all males in the server search = p.Patient.where(struct={'gender': 'male'}) results = search.perform_resources(fhirServer) for r in results: print(r.as_json()['name'][0]['given'][0]) #Will print patient ID's for all patients with a recorded systolic BP search = o.Observation.where(struct={'code-value-concept': '8480-6'}) results = search.perform_resources(fhirServer) for r in results: print(r.as_json()['subject']['reference'])
def runCohortCounter(endpointUrl, endpointToken): #connect to FHIR server smart = client.FHIRClient(settings={ 'app_id': endpointToken, 'api_base': endpointUrl }) urlBase = endpointUrl #Patients diagnosed with diabetes print('Patient cohort for Diabetes') search_str = 'Condition?_include=Condition:patient&code:below=http://snomed.info/sct|73211009' # print('Patient cohort for asthma') #search_str = 'Condition?_include=Condition:patient&code=195917001' cohort = perform_in(search_str, smart.server, urlBase) results = len(cohort) cohortSize = int(results / 2) print("Retrieved cohort size %s" % cohortSize) ageSum = 0 def calculate_age(born): # convert str to datetime format dob = datetime.strptime(born, "%Y-%m-%d") today = date.today() return today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day)) # Loop over all patients in bundle for patients in cohort: entry = patients.as_json() if 'birthDate' in entry.keys(): dob = entry['birthDate'] age_i = calculate_age(dob) ageSum = ageSum + age_i else: results = results - 1 print("Cohort size after eliminating patients with no age data: %s" % results) # Calculate mean age meanAge = None if cohortSize > 0: meanAge = ageSum / results print("Mean age in cohort: %s" % meanAge) return {'cohortCount': results, 'meanAge': meanAge}