Aditya9605/CKD
1
1import os
2import pymongo
3from pymongo import MongoClient
4from bson.objectid import ObjectId
5import datetime
6
7# MongoDB Configuration
8MONGO_URI = os.getenv("MONGO_URI")
9DB_NAME = "doctor_dashboard_db"
10
11def get_db_connection():
12 """
13 Returns a MongoDB database object.
14 Requires MONGO_URI to be set in environment variables.
15 """
16 if not MONGO_URI:
17 # Fallback for local testing if user hasn't set it, or raise error
18 print("Warning: MONGO_URI not found. Trying localhost default.")
19 client = MongoClient("mongodb://localhost:27017/")
20 else:
21 # FIX: Parse and escape username/password to handle special characters
22 try:
23 from urllib.parse import quote_plus, urlparse
24
25 # Check if URI contains user info
26 if "@" in MONGO_URI:
27 # Basic parsing to extract credentials - this is a simple heuristic
28 # A robust way is to ask user to provide escaped URI, but we can try to fix standard cases
29 # If the user already provided a full URI, it might be that they didn't escape it.
30 # However, re-assembling a URI is risky if we don't know exactly what part is what.
31 # BETTER APPROACH: Trust standard MongoClient but warn user,
32 # OR if you are using `username:password` format, ensure they are escaped.
33
34 # Given the error is "Username and password must be escaped",
35 # it means the user likely has special chars like '@' or ':' in their password.
36 pass
37
38 # The error explicitly suggests usage of quote_plus.
39 # Since we can't easily parse an invalid URI to fix it automatically without potentially breaking other parts,
40 # We will catch the error and print a helpful message, OR we can try to be smart if the env var is just the connection string.
41
42 client = MongoClient(MONGO_URI)
43 except Exception as e:
44 print(f"Error connecting to MongoDB: {e}")
45 print("TIP: If your password contains special characters like '@', ':', or '/', you must URL-encode them.")
46 print("Example: 'p@ssword' becomes 'p%40ssword'.")
47 # Re-raise to stop execution as DB is critical
48 raise e
49
50 db = client[DB_NAME]
51 return db
52
53def init_db():
54 """
55 Initializes the database with seed data if empty.
56 """
57 db = get_db_connection()
58 patients_col = db['patients']
59
60 # Check if empty
61 if patients_col.count_documents({}) == 0:
62 seed_data = [
63 {
64 "name": "Arjun Kumar",
65 "age": 45,
66 "gender": "Male",
67 "contact": "9876543210",
68 "history": "Diagnosed with Stage 2 CKD in 2024. Hypertension (managed). Family history of diabetes.",
69 "last_visit": "2024-10-15"
70 },
71 {
72 "name": "Priya Sharma",
73 "age": 62,
74 "gender": "Female",
75 "contact": "8765432109",
76 "history": "Stage 3 CKD. High creatinine levels. Regular dialysis patient.",
77 "last_visit": "2024-11-01"
78 },
79 {
80 "name": "Rahul Verma",
81 "age": 38,
82 "gender": "Male",
83 "contact": "7654321098",
84 "history": "Early signs of kidney stones. Recommended increased fluid intake.",
85 "last_visit": "2024-11-10"
86 }
87 ]
88 patients_col.insert_many(seed_data)
89 print("Initialized MongoDB with seed data.")
90
91def get_all_patients():
92 """
93 Retrieves all patients.
94 Converts _id to string 'id'.
95 """
96 db = get_db_connection()
97 patients = list(db['patients'].find())
98 for p in patients:
99 p['id'] = str(p['_id'])
100 del p['_id']
101 return patients
102
103def get_patient(patient_id):
104 """
105 Retrieves a single patient by ID.
106 Handles ObjectId conversion.
107 """
108 db = get_db_connection()
109 try:
110 obj_id = ObjectId(patient_id)
111 patient = db['patients'].find_one({"_id": obj_id})
112 if patient:
113 patient['id'] = str(patient['_id'])
114 del patient['_id']
115 return patient
116 except Exception as e:
117 print(f"Error fetching patient {patient_id}: {e}")
118 return None
119
120def add_patient(name, age=None, gender=None, contact=None, history=None, last_visit=None):
121 """
122 Adds a new patient.
123 Returns the new patient's ID as a string.
124 """
125 db = get_db_connection()
126 new_patient = {
127 "name": name,
128 "age": age,
129 "gender": gender,
130 "contact": contact,
131 "history": history,
132 "last_visit": last_visit if last_visit else datetime.datetime.now().strftime("%Y-%m-%d")
133 }
134 result = db['patients'].insert_one(new_patient)
135 return str(result.inserted_id)
136 