You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI Depends对象无query属性问题及跨端点数据库访问阻塞求助

问题
  • 在FastAPI项目中,/refresh等端点通过Depends获取数据库会话正常工作,但/token路由添加database: Session = Depends(db_handler.get_db)参数时,抛出错误:'Depends' object has no attribute 'query'
  • 为绕开Depends的限制,创建/set-users端点并在/login中调用,结果请求陷入阻塞无法完成
解决方案

1. 修复/token路由的依赖解析问题

你使用了@router.route('/token')通用路由装饰器,FastAPI对这种方式的依赖解析支持有限,建议使用对应HTTP方法的装饰器(OAuth token端点通常为POST),确保Depends能正确解析为数据库会话:

修改前:

@router.route('/token')
async def auth(request: Request, database: Session = Depends(db_handler.get_db)):

修改后:

@router.post('/token')  # 明确指定POST方法
async def auth(request: Request, database: Session = Depends(db_handler.get_db)):

之后即可取消注释原有数据库操作代码:

emails = brand_operation_handler.get_all_users(db=database)
allowed_email_in_user_table_setter(emails)

2. 解决/login端点请求阻塞问题

requests.post是同步HTTP请求,在async函数中调用会阻塞整个事件循环,导致请求挂起。替换为异步HTTP客户端(如httpx.AsyncClient):

首先安装依赖:

pip install httpx

修改/login端点代码:

import httpx  # 导入异步客户端

@router.route('/login')
async def login(request: Request):
    # 使用异步客户端发起请求
    async with httpx.AsyncClient() as client:
        await client.post(url="http://localhost:8000/auth/set-users")
    
    redirect_uri = FRONTEND_URL
    return await oauth.google.authorize_redirect(request, redirect_uri)

额外优化建议

无需通过调用内部端点的方式同步邮箱列表,直接在需要的地方(如/token或/login)直接获取数据库会话并执行操作,减少不必要的HTTP请求:

@router.route('/login')
async def login(request: Request, database: Session = Depends(db_handler.get_db)):
    emails = brand_operation_handler.get_all_users(db=database)
    allowed_email_in_user_table_setter(emails)
    
    redirect_uri = FRONTEND_URL
    return await oauth.google.authorize_redirect(request, redirect_uri)

内容的提问来源于stack exchange,提问作者angelo isola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 02:50:42