[英]Python asyncio context
在線程中,我們有一個名為“線程上下文”的東西,我們可以在其中保存一些數據(狀態)以便在特殊線程中進行訪問。 在asyncio中,我需要在當前執行路徑中保存一些狀態,以便所有后續協同程序都可以訪問它。 解決辦法是什么? 注意:我知道每個協同程序函數都是為asyncio中的執行路徑實例化的,但由於某種原因,我無法將狀態保存在函數屬性中。 (雖然這種方法反正不太好)
從Python 3.7開始,您可以使用contextvars.ContextVar 。
在下面的示例中,我聲明了request_id並在some_outer_coroutine中設置了值,然后在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
還有https://github.com/azazel75/metapensiero.asyncio.tasklocal ,但你必須意識到任務通常是由庫內部創建的,也是由asyncio使用ensure_future(a_coroutine)
並且沒有實際的方法來跟蹤這些新任務並初始化他們的本地人(可能與他們創建的任務的那些)。 (“hack”應該設置loop.set_task_factory()
函數來完成工作,希望所有代碼都使用loop.create_task()
來創建任務,這並不總是正確的......)
另一個問題是,如果你的一些代碼是在一個Future回調Task.current_task()
函數中執行的,那么兩個庫使用它來選擇要服務的本地副本的正確副本將始終返回None
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.