【发布时间】:2021-11-13 21:59:56
【问题描述】:
在 FastAPI 上,我有一个端点调用下面的 get_1 或 get_2 协程函数。
get_1 使用 await redis.get(key)
get_2 使用await asyncio.ensure_future(redis.get(key))
这两个函数在功能和性能方面有什么区别吗?
#redis.py
import asyncio
import aioredis
async def get_1(key):
redis = aioredis.from_url("redis://localhost")
value = await redis.get(key)
return value
async def get_2(key):
redis = aioredis.from_url("redis://localhost")
value = await asyncio.ensure_future(redis.get(key))
return value
【问题讨论】:
-
我怀疑
get_2()是更旧的代码。随着 Python 的每个版本,异步框架变得更加简洁。asyncio.ensure_future是一个低级 API,应该不再需要在大多数代码中使用它。 -
我同意较新的 Python,
get_2()应该使用asyncio.create_task。那我还是有同样的问题。
标签: python asynchronous python-asyncio fastapi aioredis