python runtime_error ai_generated true

AssertionError: Dependency cache is not cleared

ID: python/fastapi-dependency-cache-not-cleared

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

FastAPI caches dependency results per request; improper use of global state or yield dependencies can cause stale data.

generic

中文

FastAPI 缓存每个请求的依赖结果;错误使用全局状态或 yield 依赖可能导致数据过期。

Workarounds

  1. 90% success
    Use yield dependencies properly: def get_db():
        db = Session()
        try:
            yield db
        finally:
            db.close()
  2. 85% success
    Set use_cache=False for dependencies that should not cache: Depends(get_db, use_cache=False)

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Global state persists across requests; cache not cleared between requests.

  2. 60% fail

    FastAPI automatically caches; need to use yield for cleanup.