Add mongodb connection support

This commit is contained in:
Peter Vacho 2024-11-27 16:39:23 +01:00
parent b6b7c466db
commit ed540eeca3
Signed by: school
GPG key ID: 8CFC3837052871B4
6 changed files with 28 additions and 1 deletions

View file

@ -9,6 +9,7 @@ dependencies = [
"poethepoet>=0.31.1",
"python-decouple>=3.8",
"coloredlogs>=15.0.1",
"motor[srv]>=3.6.0",
]
readme = "README.md"
requires-python = ">= 3.12"

View file

@ -23,6 +23,8 @@ coloredlogs==15.0.1
# via event-management
distlib==0.3.9
# via virtualenv
dnspython==2.7.0
# via pymongo
fastapi==0.115.5
# via event-management
filelock==3.16.1
@ -35,6 +37,8 @@ identify==2.6.3
# via pre-commit
idna==3.10
# via anyio
motor==3.6.0
# via event-management
nodeenv==1.9.1
# via pre-commit
nodejs-wheel-binaries==22.11.0
@ -50,6 +54,8 @@ pydantic==2.10.2
# via fastapi
pydantic-core==2.27.1
# via pydantic
pymongo==4.9.2
# via motor
python-decouple==3.8
# via event-management
pyyaml==6.0.2

View file

@ -18,6 +18,8 @@ click==8.1.7
# via uvicorn
coloredlogs==15.0.1
# via event-management
dnspython==2.7.0
# via pymongo
fastapi==0.115.5
# via event-management
h11==0.14.0
@ -26,6 +28,8 @@ humanfriendly==10.0
# via coloredlogs
idna==3.10
# via anyio
motor==3.6.0
# via event-management
pastel==0.2.1
# via poethepoet
poethepoet==0.31.1
@ -34,6 +38,8 @@ pydantic==2.10.2
# via fastapi
pydantic-core==2.27.1
# via pydantic
pymongo==4.9.2
# via motor
python-decouple==3.8
# via event-management
pyyaml==6.0.2

View file

@ -7,7 +7,9 @@ from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.requests import Request
from fastapi.responses import HTMLResponse, PlainTextResponse
from motor.motor_asyncio import AsyncIOMotorClient
from src.settings import MONGODB_URI
from src.utils.logging import get_logger
log = get_logger(__name__)
@ -16,15 +18,24 @@ __all__ = ["app"]
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
"""Context manager wrapping the FastAPI app, to handle initialization and exit cleanup."""
log.info("Initialization complete.")
app.state.db_client = AsyncIOMotorClient(MONGODB_URI)
app.state.database = app.state.db_client.get_default_database()
ping_response = await app.state.database.command("ping")
if int(ping_response["ok"]) != 1:
raise ConnectionError("Database connection failed")
else:
log.info("Connected to MongoDB")
try:
yield
except CancelledError:
log.info("Stopping...")
finally:
app.state.db_client.close()
log.info("Cleanup complete.")

View file

@ -5,3 +5,5 @@ from src.utils.config import get_config
DEBUG = get_config("DEBUG", cast=bool, default=False)
LOG_FILE = get_config("LOG_FILE", cast=Path, default=None)
TRACE_LEVEL_FILTER = get_config("TRACE_LEVEL_FILTER", default=None)
MONGODB_URI = get_config("MONGODB_URI")

View file

@ -179,5 +179,6 @@ def _setup_external_log_levels(root_log: LoggerClass) -> None: # pyright: ignor
"""
get_logger("asyncio").setLevel(logging.INFO)
get_logger("multipart").setLevel(logging.INFO) # FastAPI HTTP forms parsing lib
get_logger("pymongo").setLevel(logging.INFO)
get_logger("parso").setLevel(logging.WARNING) # For usage in IPython