Issue
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)
Solution
As of Python 3.7 you can make use of contextvars.ContextVar.
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())
Output:
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
Answered By - Ramil Aglyautdinov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.