关于以下SO答案。为了理解使用 Contextvars 和不使用 Contextvars 之间的区别,我做了一些更改。
我希望在某个时候变量myid会被破坏,但将范围更改为更高的数字似乎根本没有影响。
import asyncio
import contextvars
# declare context var
request_id = contextvars.ContextVar('Id of request.')
async def some_inner_coroutine(myid):
# get value
print('Processed inner coroutine of myid : {}'.format(myid))
print('Processed inner coroutine of request: {}'.format(request_id.get()))
if myid != request_id.get():
print("ERROR")
async def some_outer_coroutine(req_id):
# set value
request_id.set(req_id)
await some_inner_coroutine(req_id)
# get value
print('Processed outer coroutine of request: {}'.format(request_id.get()))
async def main():
tasks = []
for req_id in range(1, 1250):
tasks.append(asyncio.create_task(some_outer_coroutine(req_id)))
await asyncio.gather(*tasks)
if …Run Code Online (Sandbox Code Playgroud) get_1在 FastAPI 上,我有一个调用下面的协程函数的端点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
Run Code Online (Sandbox Code Playgroud)