freeleaps-service-hub/apps/notification/webapi/providers/database.py

50 lines
1.4 KiB
Python

from webapi.config.site_settings import site_settings
from beanie import init_beanie
from motor.motor_asyncio import AsyncIOMotorClient
from backend.models.models import MessageTemplateDoc, EmailSenderDoc, EmailSendStatusDoc, EmailTrackingDoc, EmailBounceDoc
import os
# MongoDB config
MONGODB_URI = os.getenv('MONGODB_URI', 'mongodb+srv://jetli:8IHKx6dZK8BfugGp@freeleaps2.hanbj.mongodb.net/')
MONGODB_NAME = os.getenv('MONGODB_NAME', 'freeleaps2')
# create MongoDB client
client = AsyncIOMotorClient(
MONGODB_URI,
serverSelectionTimeoutMS=60000,
minPoolSize=5,
maxPoolSize=20,
heartbeatFrequencyMS=20000,
)
# define all document models
document_models = [
MessageTemplateDoc,
EmailSenderDoc,
EmailSendStatusDoc,
EmailTrackingDoc,
EmailBounceDoc
]
def register(app):
app.debug = site_settings.DEBUG
app.title = site_settings.NAME
@app.on_event("startup")
async def start_database():
await initiate_database()
async def initiate_database():
"""initiate Beanie database connection"""
try:
await init_beanie(
database=client[MONGODB_NAME],
document_models=document_models
)
print(f"✅ database initialized successfully: {MONGODB_NAME}")
print(f" URI: {MONGODB_URI}")
except Exception as e:
print(f"❌ database initialization failed: {e}")
raise