mirror of
https://github.com/fastapi/fastapi.git
synced 2026-03-02 05:37:08 -05:00
* Make compatible with pydantic v1 * Remove unused import * Remove unused ignores * Update pydantic version * Fix minor formatting issue * ⏪ Revert removing iterate_in_threadpool * ✨ Add backwards compatibility with Pydantic 0.32.2 with deprecation warnings * ✅ Update tests to not break when using Pydantic < 1.0.0 * 📝 Update docs for Pydantic version 1.0.0 * 📌 Update Pydantic range version to support from 0.32.2 * 🎨 Format test imports * ✨ Add support for Pydantic < 1.2 for populate_validators * ✨ Add backwards compatibility for Pydantic < 1.2.0 with required fields * 📌 Relax requirement for Pydantic to < 2.0.0 🎉 🚀 * 💚 Update pragma coverage for older Pydantic versions
47 lines
1.4 KiB
Python
47 lines
1.4 KiB
Python
from typing import Any, Callable
|
|
|
|
from starlette.concurrency import iterate_in_threadpool # noqa
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
asynccontextmanager_error_message = """
|
|
FastAPI's contextmanager_in_threadpool require Python 3.7 or above,
|
|
or the backport for Python 3.6, installed with:
|
|
pip install async-generator
|
|
"""
|
|
|
|
|
|
def _fake_asynccontextmanager(func: Callable) -> Callable:
|
|
def raiser(*args: Any, **kwargs: Any) -> Any:
|
|
raise RuntimeError(asynccontextmanager_error_message)
|
|
|
|
return raiser
|
|
|
|
|
|
try:
|
|
from contextlib import asynccontextmanager # type: ignore
|
|
except ImportError:
|
|
try:
|
|
from async_generator import asynccontextmanager # type: ignore
|
|
except ImportError: # pragma: no cover
|
|
asynccontextmanager = _fake_asynccontextmanager
|
|
|
|
try:
|
|
from contextlib import AsyncExitStack # type: ignore
|
|
except ImportError:
|
|
try:
|
|
from async_exit_stack import AsyncExitStack # type: ignore
|
|
except ImportError: # pragma: no cover
|
|
AsyncExitStack = None # type: ignore
|
|
|
|
|
|
@asynccontextmanager
|
|
async def contextmanager_in_threadpool(cm: Any) -> Any:
|
|
try:
|
|
yield await run_in_threadpool(cm.__enter__)
|
|
except Exception as e:
|
|
ok = await run_in_threadpool(cm.__exit__, type(e), e, None)
|
|
if not ok:
|
|
raise e
|
|
else:
|
|
await run_in_threadpool(cm.__exit__, None, None, None)
|