-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·72 lines (56 loc) · 2.06 KB
/
main.py
File metadata and controls
executable file
·72 lines (56 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
from app.config import IS_PRODUCTION, templates
from app.database import db
from app.routers import paste, user
from app.utils import AuthMiddleware
async def background_cleanup():
while True:
try:
await asyncio.sleep(7200)
deleted = await db.delete_expired_pastes()
if deleted > 0:
print(f"Cleaned up {deleted} expired pastes.")
except asyncio.CancelledError:
return
except Exception as e:
print(f"Cleanup error: {e}")
await asyncio.sleep(600)
async def background_view_flush():
while True:
try:
await asyncio.sleep(120)
await paste.flush_views_buffer()
except asyncio.CancelledError:
return
except Exception as e:
print(f"View flush error: {e}")
await asyncio.sleep(60)
@asynccontextmanager
async def lifespan(app: FastAPI):
await db.connect()
cleanup_task = asyncio.create_task(background_cleanup())
view_task = asyncio.create_task(background_view_flush())
yield
cleanup_task.cancel()
view_task.cancel()
await paste.flush_views_buffer()
await db.close()
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None)
app.add_middleware(AuthMiddleware)
if not IS_PRODUCTION:
app.add_middleware(GZipMiddleware, minimum_size=5_000)
app.mount("/static", StaticFiles(directory="static"), name="static")
app.include_router(user.router)
app.include_router(paste.api_router)
app.include_router(paste.router)
@app.exception_handler(303)
async def redirect_303_handler(request: Request, __):
return RedirectResponse(url="/login", status_code=303)
@app.exception_handler(404)
async def not_found_handler(request: Request, __):
return templates.TemplateResponse("404.html", {"request": request}, status_code=404)