Update database.py
Browse files- database.py +43 -46
database.py
CHANGED
|
@@ -1,46 +1,43 @@
|
|
| 1 |
-
import motor.motor_asyncio
|
| 2 |
-
import os
|
| 3 |
-
import logging
|
| 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 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
logger.info("Closing MongoDB connection")
|
| 45 |
-
client.close()
|
| 46 |
-
client = None
|
|
|
|
| 1 |
+
import motor.motor_asyncio
|
| 2 |
+
import os
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
logging.basicConfig(level=logging.INFO)
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
|
| 8 |
+
MONGO_URI = os.getenv("MONGO_URI")
|
| 9 |
+
if not MONGO_URI:
|
| 10 |
+
raise ValueError("MONGO_URI is not set")
|
| 11 |
+
|
| 12 |
+
logger.info("Connecting to MongoDB")
|
| 13 |
+
|
| 14 |
+
client = None
|
| 15 |
+
db = None
|
| 16 |
+
users_collection = None
|
| 17 |
+
|
| 18 |
+
async def get_database():
|
| 19 |
+
global client, db, users_collection
|
| 20 |
+
|
| 21 |
+
if client is None:
|
| 22 |
+
try:
|
| 23 |
+
logger.info("Connecting to MongoDB")
|
| 24 |
+
client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI)
|
| 25 |
+
db = client["fastapi_db"]
|
| 26 |
+
users_collection = db["users"]
|
| 27 |
+
logger.info("Successfully connected to MongoDB")
|
| 28 |
+
except Exception as e:
|
| 29 |
+
logger.error(f"MongoDB connection failed: {e}")
|
| 30 |
+
raise
|
| 31 |
+
|
| 32 |
+
return db
|
| 33 |
+
|
| 34 |
+
async def get_users_collection():
|
| 35 |
+
await get_database()
|
| 36 |
+
return users_collection
|
| 37 |
+
|
| 38 |
+
async def close_database():
|
| 39 |
+
global client
|
| 40 |
+
if client:
|
| 41 |
+
logger.info("Closing MongoDB connection")
|
| 42 |
+
client.close()
|
| 43 |
+
client = None
|
|
|
|
|
|
|
|
|