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

28
app.py
View file

@ -1,12 +1,13 @@
import logging
from fastapi import FastAPI, Request
from src.core.config.config import Settings, get_settings
from src.core.events.events import shutdown_app, startup_app
from src.main import global_router
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi_jwt_auth.exceptions import AuthJWTException
from src.services.mocks.initial import create_initial_data
import pymongo
########################
# Pre-Alpha Version 0.1.0
@ -14,7 +15,6 @@ import pymongo
# (c) LearnHouse 2022
########################
# Global Config
app = FastAPI(
title="LearnHouse",
@ -23,6 +23,7 @@ app = FastAPI(
root_path="/"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000", "http://localhost:3001"],
@ -35,24 +36,10 @@ app.add_middleware(
app.mount("/content", StaticFiles(directory="content"), name="content")
# Lifecycle Events
@app.on_event("startup")
def startup_event():
logging.info("Starting LearnHouse...")
# Database Connection
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)
# Events
app.add_event_handler("startup", startup_app(app))
app.add_event_handler("shutdown", shutdown_app(app))
@app.on_event("shutdown")
def shutdown_event():
app.mongodb_client.close() # type: ignore
logging.info("LearnHouse has been shut down.")
# JWT Exception Handler
@app.exception_handler(AuthJWTException)
@ -62,10 +49,13 @@ def authjwt_exception_handler(request: Request, exc: AuthJWTException):
content={"detail": exc.message} # type: ignore
)
# Global Routes
app.include_router(global_router)
# General Routes
@app.get("/")
async def root():
return {"Message": "Welcome to LearnHouse ✨"}

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