DB and FastAPI: Reconnect if DB goes down, switch to lifespan events in FastAPI, ensure safe startup/shutdown.
This commit is contained in:
1 parent
2a8d06a373
commit
799ecdda67
3 files changed
+41
-6
No files matched your search
+18
-3
@@ -1,4 +1,4 @@
|
||||
from fastapi import FastAPI, Depends, HTTPException
|
||||
from fastapi import FastAPI, Depends, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.security.api_key import APIKeyHeader
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
@@ -6,12 +6,13 @@ from typing import Optional,List
|
||||
from pydantic import BaseModel
|
||||
from validator import is_valid_platform,is_valid_token,verify_api_key
|
||||
from secret_handler import encrypt_token
|
||||
from db import get_db
|
||||
from db import get_db, create_connection_pool, close_connection_pool
|
||||
from logger_handler import setup_logger
|
||||
import uuid
|
||||
from hashlib import sha256
|
||||
import uvicorn
|
||||
from uvicorn_logging_config import LOGGING_CONFIG
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
|
||||
|
||||
@@ -31,10 +32,24 @@ class TokenRequest(BaseModel):
|
||||
locale : Optional[str] = None
|
||||
topics : Optional[List[str]] = None
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
logger.info("Starting application...")
|
||||
|
||||
logger.info("Creating MySQL connection pool...")
|
||||
create_connection_pool()
|
||||
|
||||
yield
|
||||
logger.info("Closing MySQL connection pool...")
|
||||
close_connection_pool()
|
||||
|
||||
|
||||
api = FastAPI(
|
||||
title="Device Token Management",
|
||||
description="API for requesting tokens",
|
||||
version="1.0.0"
|
||||
version="1.0.0",
|
||||
lifespan=lifespan
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user