Python异步上下文 [英] Python asyncio context
问题描述
在线程中,我们有一个称为线程上下文"的东西,在其中我们可以保存一些数据(状态),以便在特殊线程中进行访问.在异步中,我需要在当前执行路径中保存一些状态,以便所有后续协程都可以访问它.解决办法是什么?注意:我知道每个协程函数都为asyncio中的执行路径实例化,但是由于某些原因,我无法将状态保存在函数属性中.(尽管这种方法仍然不是很好)
In threading, we have something called "Thread Context", in which we can save some data (state) for accessing in a special thread. In asyncio, I need to save some state in current execution path, so that all consequent coroutines can access it. What is the solution? Note: I know each coroutine function is instantiated for an execution path in asyncio, but for some reason I can not save the state in function properties. (Although this method os not very good anyway)
推荐答案
As of Python 3.7 you can make use of contextvars.ContextVar.
在下面的示例中,我声明了 request_id ,并在 some_outer_coroutine 中设置了值,然后在 some_inner_coroutine 中对其进行了访问.
In the example below I declared request_id and set the value in some_outer_coroutine, then accessed it in some_inner_coroutine.
import asyncio
import contextvars
# declare context var
request_id = contextvars.ContextVar('Id of request.')
async def some_inner_coroutine():
# get value
print('Processed inner coroutine of request: {}'.format(request_id.get()))
async def some_outer_coroutine(req_id):
# set value
request_id.set(req_id)
await some_inner_coroutine()
# get value
print('Processed outer coroutine of request: {}'.format(request_id.get()))
async def main():
tasks = []
for req_id in range(1, 5):
tasks.append(asyncio.create_task(some_outer_coroutine(req_id)))
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(main())
输出:
Processed inner coroutine of request: 1
Processed outer coroutine of request: 1
Processed inner coroutine of request: 2
Processed outer coroutine of request: 2
Processed inner coroutine of request: 3
Processed outer coroutine of request: 3
Processed inner coroutine of request: 4
Processed outer coroutine of request: 4
这篇关于Python异步上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!