python runtime_error ai_generated true

AttributeError: 'State' object has no attribute 'db'

ID: python/starlette-state-access-error

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

尝试访问Starlette应用state对象中未设置的属性,例如数据库连接。

generic

中文

尝试访问Starlette应用state对象中未设置的属性,例如数据库连接。

Workarounds

  1. 95% success 在应用启动事件中初始化state属性
    from starlette.applications import Starlette; app = Starlette(); @app.on_event('startup') async def startup(): app.state.db = await create_db_connection()
  2. 90% success 在访问前检查属性是否存在
    if hasattr(app.state, 'db'): await app.state.db.execute(query)

Dead Ends

Common approaches that don't work:

  1. 在路由中直接使用app.state.db而未初始化 90% fail

    state对象为空。

  2. 使用全局变量存储数据库连接 70% fail

    可能导致连接泄露。