python runtime_error ai_generated true

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

ID: python/fastapi-background-task-exception

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-12-04First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100+ active — — —
0.110+ active — — —

Root Cause

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

generic

中文

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

Workarounds

  1. 92% success
    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% success
    Use a task queue (Celery/RQ) for long-running or dependency-heavy work.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Silences the error but the task never runs correctly.

  2. 80% fail

    Blocks the response; defeats the purpose of background tasks.