{
  "id": "python/fastapi-async-sync-mixing",
  "signature": "RuntimeError: You cannot use async generator in sync context",
  "signature_zh": "运行时错误：不能在同步上下文中使用异步生成器。",
  "regex": "RuntimeError:\\ You\\ cannot\\ use\\ async\\ generator\\ in\\ sync\\ context",
  "domain": "python",
  "category": "runtime_error",
  "subcategory": null,
  "root_cause": "Mixing async and sync code incorrectly in FastAPI dependencies or route handlers, e.g., calling async functions from sync endpoints.",
  "root_cause_type": "generic",
  "root_cause_zh": "在 FastAPI 依赖或路由处理器中错误地混合异步和同步代码，例如在同步端点中调用异步函数。",
  "versions": [
    {
      "version": "3.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "asyncio.run() cannot be called from a running event loop; causes RuntimeError.",
      "fail_rate": 0.9,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "Calling async function returns coroutine object, not result; must be awaited.",
      "fail_rate": 0.85,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.95,
      "how": "Define endpoint as async def if using async functions: @app.get('/')\nasync def read_root():\n    result = await some_async_function()",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.9,
      "how": "Use anyio.to_thread.run_sync for sync functions in async context: from anyio import to_thread\nresult = await to_thread.run_sync(sync_function)",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.84,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-06-15",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}