22 lines
538 B
Python
22 lines
538 B
Python
from motor.motor_asyncio import AsyncIOMotorClient
|
|
from .config import settings
|
|
|
|
class Database:
|
|
client: AsyncIOMotorClient = None
|
|
|
|
db = Database()
|
|
|
|
def get_database():
|
|
"""Dependency to retrieve the MongoDB database database."""
|
|
if db.client is None:
|
|
# Fallback if connection wasn't explicitly started via lifespan
|
|
connect_db()
|
|
return db.client[settings.database_name]
|
|
|
|
def connect_db():
|
|
db.client = AsyncIOMotorClient(settings.mongodb_uri)
|
|
|
|
def close_db():
|
|
if db.client:
|
|
db.client.close()
|