Add database cleanup scheduler

This commit is contained in:
Parker M. 2024-12-19 16:35:18 -06:00
parent cfbaf8a0b2
commit 55e7ee145c
Signed by: parker
GPG Key ID: 505ED36FC12B5D5E
3 changed files with 49 additions and 1 deletions

View File

@ -6,10 +6,31 @@ from api.routes.links_routes import router as links_router
from api.routes.user_routes import router as user_router
from api.routes.log_routes import router as log_router
from typing import Annotated
from apscheduler.schedulers.background import BackgroundScheduler
from contextlib import asynccontextmanager
from api.util.db_dependency import get_db
from api.util.clean_db import clean_db
from api.util.log import log
from models import Link
from config import LOG
scheduler = BackgroundScheduler()
# Handle the database cleanup scheduler
def start_scheduler():
scheduler.add_job(clean_db, "interval", days=1)
scheduler.start()
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
start_scheduler()
yield
finally:
scheduler.shutdown()
app = FastAPI(
@ -21,6 +42,7 @@ app = FastAPI(
"identifier": "Unlicense",
"url": "https://unlicense.org",
},
lifespan=lifespan,
)
app.add_middleware(

25
api/util/clean_db.py Normal file
View File

@ -0,0 +1,25 @@
import datetime
from api.util.db_dependency import get_db
from models import Link, Log
"""
Remove expired short links and their associated logs
"""
def clean_db():
db = next(get_db())
# Get all expired short links
expired_links = (
db.query(Link)
.filter(Link.expire_date < datetime.datetime.today())
.all()
)
# Delete all expired short links and their logs
for link in expired_links:
logs = db.query(Log).filter(Log.link == link.link).all()
for log in logs:
db.delete(log)
db.delete(link)

View File

@ -9,4 +9,5 @@ bcrypt==4.1.3
SQLAlchemy==2.0.31
validators==0.28.3
requests==2.32.3
ua-parser==0.18.0
ua-parser==0.18.0
APScheduler==3.11.0