FastAPI服务器/predictions接口请求时页面无限加载问题排查
问题原因与解决方案
核心问题
你在/predictions接口中使用**同步的requests.get()**调用同个服务的/county接口,导致FastAPI的异步事件循环被完全阻塞,形成死锁:
/predictions发起同步请求后,会一直占用事件循环等待响应- 此时
/county的请求根本无法被事件循环处理,自然没有返回 - 最终表现就是页面一直加载,无任何响应
两种解决办法
方法1:改用异步HTTP客户端(推荐)
使用支持异步的httpx.AsyncClient替代同步的requests,这样不会阻塞事件循环:
- 先安装依赖:
pip install httpx
- 修改
/predictions接口代码:
import httpx @app.get("/predictions", response_class=HTMLResponse) async def predictions(request: Request): async with httpx.AsyncClient() as client: response = await client.get("http://localhost:8000/county") regions = response.json()["regions"] return templates.TemplateResponse("predictions.html", {"request": request, "regions": regions})
方法2:直接复用数据库查询逻辑(更高效)
既然都是同一个服务内的逻辑,没必要走HTTP请求,直接把查询逻辑抽成函数复用:
# 抽离公共查询函数 def get_county_regions(): cursor.execute("SELECT name FROM county") return cursor.fetchall() # 原/county接口复用函数 @app.get("/county") async def get_regions(): regions = get_county_regions() return {"regions": regions} # /predictions接口直接调用函数 @app.get("/predictions", response_class=HTMLResponse) async def predictions(request: Request): regions = get_county_regions() return templates.TemplateResponse("predictions.html", {"request": request, "regions": regions})
额外注意
你当前的数据库连接和游标是全局初始化的,在多并发请求场景下容易出现连接异常或数据错乱。建议使用FastAPI的依赖注入来管理数据库连接,每次请求创建/销毁连接,保证线程安全。
内容的提问来源于stack exchange,提问作者mariniou77
相关产品推荐
相关产品推荐

