python runtime_error ai_generated true

后台任务异常:AttributeError: 'NoneType' 对象没有属性 'send_email'

Exception in background task: AttributeError: 'NoneType' object has no attribute 'send_email'

ID: python/fastapi-background-task-exception

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2024-12-04首次发现

版本兼容性

版本状态引入弃用备注
0.100+ active — — —
0.110+ active — — —

根因分析

BackgroundTasks 函数引用了请求作用域的依赖(数据库会话、current_user),而这些依赖在响应返回后即被关闭。

English

BackgroundTasks function references a request-scoped dependency (DB session, current_user) that is closed after the response is returned.

generic

解决方案

  1. 92% 成功率
    def send(uid: int):
        with SessionLocal() as s:
            user = s.get(User, uid)
            ...
    background_tasks.add_task(send, user.id)  # pass IDs, not objects
  2. 88% 成功率
    Use a task queue (Celery/RQ) for long-running or dependency-heavy work.

无效尝试

常见但无效的做法:

  1. 70% 失败

    Silences the error but the task never runs correctly.

  2. 80% 失败

    Blocks the response; defeats the purpose of background tasks.