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

SQLAlchemy查询活跃用户遇递归深度超限错误求助

解决SQLAlchemy查询活跃用户时的递归错误

问题现象

尝试获取数据库中is_active=True的活跃用户列表时,触发递归深度超出限制错误:

[Previous line repeated 991 more times]
RecursionError: maximum recursion depth exceeded

栈追踪显示错误来自路由函数内部的重复调用:

File "/Users/davethomson/git/github.com/serup.ai/serupai-backend/auth/./routers/admin.py", line 29, in get_active_users
    active_users = get_active_users()
  File "/Users/davethomson/git/github.com/serup.ai/serupai-backend/auth/./routers/admin.py", line 29, in get_active_users
    active_users = get_active_users()
  [Previous line repeated 991 more times]
RecursionError: maximum recursion depth exceeded

问题根源

路由处理函数与查询函数同名:路由中的get_active_users函数内部调用get_active_users()时,没有指向外部的查询函数,而是递归调用了自身,导致无限循环直到超出Python递归深度限制。

同时查询函数存在两处小问题:

  1. 定义中声明了limit参数但未实际使用
  2. 变体代码中return active_users写在for循环内部,只会返回第一个用户

修复方案

1. 修正查询函数(get_active_users.py)

修复缩进、启用limit参数,并简化布尔筛选条件:

def get_active_users(limit: int = 100):
    with Session(engine) as session:
        # 筛选活跃用户并应用limit限制
        return session.query(User).filter(User.is_active).limit(limit).all()

2. 修正路由函数调用

通过导入别名或修改路由函数名避免命名冲突:

方式一:使用导入别名

# 导入查询函数时添加别名,区分路由函数
from ..crud.get_active_users import get_active_users as get_active_users_db

@router.get("/users/active", response_model=List[UserAll])
def get_active_users(limit: int = 100, current_user=Depends(user_role)):
    # 调用带别名的查询函数,传入limit参数
    active_users = get_active_users_db(limit=limit)
    return active_users

方式二:修改路由函数名

from ..crud.get_active_users import get_active_users

@router.get("/users/active", response_model=List[UserAll])
# 重命名路由函数,避免与查询函数冲突
def get_active_users_route(limit: int = 100, current_user=Depends(user_role)):
    active_users = get_active_users(limit=limit)
    return active_users

额外优化建议

  • 保持函数命名区分度:比如数据层查询函数后缀加_db,路由函数后缀加_route,从根源避免命名冲突
  • SQLAlchemy中布尔字段筛选可直接写filter(User.is_active),无需== True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:01:16