fix fast async startup

This commit is contained in:
熊潇 2025-05-03 01:33:19 +08:00
parent 9cacdc1532
commit 010985d990
2 changed files with 16 additions and 13 deletions

18
app.py
View File

@ -5,11 +5,20 @@ from playwright.async_api import async_playwright # 改用异步 API
from dotenv import load_dotenv
import os
from typing import Optional, Dict, Any
from contextlib import asynccontextmanager
# 加载环境变量
load_dotenv()
app = FastAPI()
@asynccontextmanager
async def lifespan(app: FastAPI):
await initialize_playwright()
yield
# Clean up the ML models and release the resources
# await shutdown_event()
print("关闭")
app = FastAPI(lifespan=lifespan)
global_a1 = ""
# 确保在模块级别声明全局变量
@ -148,14 +157,7 @@ async def get_a1(a1: Optional[str] = None):
return {'a1': global_a1}
# 在应用启动时初始化 Playwright
@app.lifespan("startup")
async def startup_event():
await initialize_playwright()
# 在应用关闭时清理资源
@app.lifespan("shutdown")
async def shutdown_event():
global playwright_instance, browser_context, context_page
if context_page:

View File

@ -1,5 +1,6 @@
playwright
xhs
fastapi
dotenv
uvicorn
dotenv==0.9.9
fastapi==0.115.12
playwright==1.52.0
requests==2.32.3
uvicorn==0.34.2
xhs==0.2.13