Add database cleanup scheduler
This commit is contained in:
parent
cfbaf8a0b2
commit
55e7ee145c
22
api/main.py
22
api/main.py
@ -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
25
api/util/clean_db.py
Normal 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)
|
@ -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
|
Loading…
x
Reference in New Issue
Block a user