[英]Python asyncio - How to create task list and use it in the event loop?
[英]How to get task out of asyncio event loop in a view?
在使用aiohttp編寫的Web應用程序中,我有2個端點。 首先是啟動異步任務,這是無限循環。 第二個旨在取消某些任務。 由於異步任務沒有任何ID概念,我有點困惑。 是否可以在數據庫中保存任務的某些標識符? 是這樣做的正確方法,還是lib已經為此類問題提供了解決方案?
from aiohttp import web
import asyncio
import json
async def coro(frequency):
while True:
print('Infinite loop iteration')
await asyncio.sleep(frequency)
def start_task(request):
event_loop = asyncio.get_event_loop()
task = event_loop.create_task(coro())
# save some identifier of the task in the database to find it later
response = dict()
return web.json_response(json.dumps(response))
def stop_task(request):
task = None # here i must get a certain task outta event loop
task.cancel()
response = dict()
return web.json_response(json.dumps(response))
謝謝你的幫助!
您可以生成簡單的單調遞增的數字ID,並具有將ID映射到任務實例的全局指令。 協程完成后,映射將被刪除。 例如(未測試):
import asyncio, itertools
_next_id = itertools.count().__next__
_tasks = {}
def make_task(corofn, *coroargs):
task_id = _next_id()
async def wrapped_coro():
try:
return await corofn(*coroargs)
finally:
del _tasks[task_id]
task = asyncio.create_task(wrapped_coro())
_tasks[task_id] = task
return task_id, task
def get_task(task_id):
return _tasks[task_id]
然后,您可以在start_task
和stop_task
使用它:
def start_task(request):
task_id, _ = make_task(coro)
response = {'task_id': task_id}
return web.json_response(json.dumps(response))
def stop_task(request):
task_id = json.loads(await request.text())['task_id']
task = get_task(task_id)
task.cancel()
response = {}
return web.json_response(json.dumps(response))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.