1+ import requests
2+ import os
3+ from flask import Flask , request , render_template
4+ from dotenv import load_dotenv
5+
6+
7+ app = Flask (__name__ )
8+
9+ FHIR_SERVER_BASE_URL = "http://pwebmedcit.services.brown.edu:9091/fhir"
10+
11+ load_dotenv ()
12+
13+ username = os .getenv ("FHIR_USERNAME" )
14+ password = os .getenv ("FHIR_PASSWORD" )
15+
16+
17+ def request_patient (patient_id , credentials ):
18+
19+ req = requests .get (FHIR_SERVER_BASE_URL + "/Patient/" + str (patient_id ), auth = credentials )
20+
21+ print (f"Requests status: { req .status_code } " )
22+
23+ response = req .json ()
24+ print (response .keys ())
25+
26+ return response
27+
28+ def search_patients_by_condition (condition_id , credentials ):
29+ # Search for patients with a specific condition
30+ search_url = f"{ FHIR_SERVER_BASE_URL } /Condition?code={ condition_id } "
31+ req = requests .get (search_url , auth = credentials )
32+
33+ if req .status_code == 200 :
34+ conditions = req .json ()['entry' ]
35+ patient_ids = [entry ['resource' ]['subject' ]['reference' ].split ('/' )[- 1 ] for entry in conditions ]
36+ patients = [request_patient (patient_id , credentials ) for patient_id in patient_ids ]
37+ # Convert patient details into set of tuples to ensure uniqueness
38+ unique_patients = set ((patient ['id' ], patient ['name' ][0 ]['given' ][0 ], patient ['name' ][0 ]['family' ], patient ['gender' ], patient ['birthDate' ]) for patient in patients )
39+
40+ total_patients = len (unique_patients )
41+ return {'unique_patients' : unique_patients , 'total_patients' : total_patients }
42+ else :
43+ return None
44+
45+
46+
47+
48+
49+ @app .route ('/' , methods = ['GET' , 'POST' ])
50+ def index ():
51+ result = None
52+ credentials = (username , password )
53+
54+ if request .method == 'POST' :
55+ try :
56+ condition_id = request .form ['condition_id' ]
57+ result = search_patients_by_condition (condition_id , credentials )
58+ except ValueError :
59+ result = 'Invalid input. Please enter a valid condition ID.'
60+
61+ return render_template ('index.html' , result = result )
62+
63+
64+ if __name__ == '__main__' :
65+ port_str = os .environ ['FHIR_PORT' ]
66+ port_int = int (port_str )
67+ app .run (debug = True , port = port_int )
0 commit comments