Spaces:
Runtime error
Runtime error
File size: 1,033 Bytes
338ec2d 11e9a40 338ec2d 11e9a40 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import certifi
from motor.motor_asyncio import AsyncIOMotorClient
client: AsyncIOMotorClient = None
db = None
async def connect_db(uri: str, db_name: str):
global client, db
client = AsyncIOMotorClient(
uri,
serverSelectionTimeoutMS=5000,
tlsCAFile=certifi.where(),
)
db = client[db_name]
# Create indexes (non-blocking — if DB is unreachable, server still starts)
try:
await db.users.create_index("email", unique=True)
await db.devices.create_index("device_id", unique=True)
await db.vitals.create_index([("device_id", 1), ("timestamp", -1)])
await db.predictions.create_index([("device_id", 1), ("created_at", -1)])
print("[DB] Connected and indexes created.")
except Exception as e:
print(f"[DB] Warning: Could not create indexes: {e}")
print("[DB] Server will start but DB operations may fail until MongoDB is available.")
async def close_db():
if client:
client.close()
def get_db():
return db
|