python
runtime_error
ai_generated
true
RuntimeError: The ASGI application instance is not available.
ID: python/starlette-missing-app-instance
80%Fix Rate
85%Confidence
0Evidence
2024-02-28First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
尝试在Starlette应用之外访问app实例,例如在导入时或测试中未正确设置。
generic中文
尝试在Starlette应用之外访问app实例,例如在导入时或测试中未正确设置。
Workarounds
-
95% success 在应用上下文中访问app,例如通过request.app
from starlette.requests import Request; async def my_endpoint(request: Request): app = request.app; return JSONResponse({'app': str(app)}) -
90% success 在测试中使用TestClient时确保app已创建
from starlette.testclient import TestClient; from main import app; client = TestClient(app); response = client.get('/')
Dead Ends
Common approaches that don't work:
-
在模块级别直接访问app对象
80% fail
app可能尚未创建或已被回收。
-
使用全局变量存储app引用
70% fail
多线程环境下可能导致竞态条件。