chore: refactor backend events

This commit is contained in:
swve 2023-01-18 22:56:14 +01:00
parent 21df8d6de6
commit 3ea5ef0100
5 changed files with 55 additions and 19 deletions

View file

@ -0,0 +1,11 @@
from fastapi import FastAPI
class Settings(FastAPI):
title="LearnHousse",
description="LearnHouse is a new open-source platform tailored for learning experiences.",
version="0.1.0",
root_path="/"
docs_url="/docs"
async def get_settings() -> Settings:
return Settings()

View file

@ -0,0 +1,18 @@
import logging
from fastapi import FastAPI
import pymongo
async def connect_to_db(app: FastAPI) :
logging.info("Connecting to database...")
try:
app.mongodb_client = pymongo.MongoClient("mongodb://learnhouse:learnhouse@mongo:27017/") # type: ignore
app.db = app.mongodb_client["learnhouse"] # type: ignore
logging.info("Connected to database!")
except Exception as e:
logging.error("Failed to connect to database!")
logging.error(e)
async def close_database(app: FastAPI):
app.mongodb_client.close() # type: ignore
logging.info("LearnHouse has been shut down.")
return app

17
src/core/events/events.py Normal file
View file

@ -0,0 +1,17 @@
from typing import Callable
from fastapi import FastAPI
from src.core.events.database import close_database, connect_to_db
def startup_app(app: FastAPI) -> Callable:
async def start_app() -> None:
# Connect to database
await connect_to_db(app)
return start_app
def shutdown_app(app: FastAPI) -> Callable:
async def close_app() -> None:
await close_database(app)
return close_app