【发布时间】:2021-11-26 11:43:49
【问题描述】:
tl;dr
- 以下哪个选项是
fastapi中正确的工作流程? - 如何以编程方式测试呼叫是否真正阻塞(除了从浏览器手动)?
uvicorn或fastapi是否有压力测试扩展?
我在fastapi 服务器中有许多端点(目前使用uvicorn),它们对常规同步 Python 代码的调用有很长时间的阻塞。尽管有文档 (https://fastapi.tiangolo.com/async/),但我仍然不清楚我是否应该专门使用 def、async def 或混合用于我的功能。
据我所知,我有三个选择,假设:
def some_long_running_sync_function():
...
选项 1 - 始终将def 仅用于端点
@app.get("route/to/endpoint")
def endpoint_1:
some_long_running_sync_function()
@app.post("route/to/another/endpoint")
def endpoint_2:
...
选项 2 - 始终使用 async def 并在执行程序中运行阻塞同步代码
import asyncio
@app.get("route/to/endpoint")
async def endpoint_1:
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, some_long_running_sync_function)
@app.post("route/to/another/endpoint")
async def endpoint_2:
...
选项 3 - 根据底层调用混合搭配 def 和 async def
import asyncio
@app.get("route/to/endpoint")
def endpoint_1:
# endpoint is calling to sync code that cannot be awaited
some_long_running_sync_function()
@app.post("route/to/another/endpoint")
async def endpoint_2:
# this code can be awaited so I can use async
...
【问题讨论】:
标签: python-asyncio fastapi uvicorn