python
runtime_error
ai_generated
true
Exception in background task: AttributeError: 'NoneType' object has no attribute 'send_email'
ID: python/fastapi-background-task-exception
80%Fix Rate
84%Confidence
0Evidence
2024-12-04First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
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 -
88% success
Use a task queue (Celery/RQ) for long-running or dependency-heavy work.
Dead Ends
Common approaches that don't work:
-
70% fail
Silences the error but the task never runs correctly.
-
80% fail
Blocks the response; defeats the purpose of background tasks.