asyncio improvement
This commit is contained in:
24
main.py
24
main.py
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
import asyncio
|
||||
from fastapi import FastAPI, Request, Depends, HTTPException
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
from starlette.staticfiles import StaticFiles
|
||||
@@ -23,6 +24,20 @@ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
STATIC_DIR = os.path.join(BASE_DIR, "static")
|
||||
TEMPLATES_DIR = os.path.join(BASE_DIR, "templates")
|
||||
|
||||
@asynccontextmanager
|
||||
async def background_listener_startup(app: FastAPI):
|
||||
"""A non-blocking task to start listeners after the app has started."""
|
||||
print("Background task: Starting listeners for all users...")
|
||||
db = SessionLocal()
|
||||
users = db.query(models.User).all()
|
||||
db.close()
|
||||
for user in users:
|
||||
# Use try/except to ensure one failing listener doesn't stop others
|
||||
try:
|
||||
await app.state.listener_manager.start_listener_for_user(user, app.state.websocket_manager)
|
||||
except Exception as e:
|
||||
print(f"ERROR: Failed to start listener for user {user.id} ({user.username}): {e}")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# This code runs on startup
|
||||
@@ -32,13 +47,8 @@ async def lifespan(app: FastAPI):
|
||||
models.Base.metadata.create_all(bind=engine)
|
||||
print("Application startup: Database tables created.")
|
||||
|
||||
# Start listeners for all existing users
|
||||
db = SessionLocal()
|
||||
users = db.query(models.User).all()
|
||||
db.close()
|
||||
for user in users:
|
||||
await app.state.listener_manager.start_listener_for_user(user, app.state.websocket_manager)
|
||||
|
||||
# Decouple listener startup from the main application startup
|
||||
asyncio.create_task(background_listener_startup(app))
|
||||
yield
|
||||
|
||||
# This code runs on shutdown
|
||||
|
||||
Reference in New Issue
Block a user