在Aiohttp应用程序中管理长时间运行的任务

问题描述 投票:1回答:1

我在Aiohttp有一个Web应用程序。

如何管理长时间运行的任务?我看到了这种情况。这是坏事还是好事?

  1. 用户请求一些长时间运行的任务。
  2. 服务器使用new_task = asyncio.create_task()创建任务为新任务生成uuid并将其全部保存在dict中:
new_task = asyncio.create_task()
uuid_task = uuid.uuid4()
tasks_set.update({
    uuid_task: new_task
})
  1. 将答案发送给状态为202 Accepted和task's uuid的客户端。
  2. 一段时间后,用户使用任务uuid​​请求任务的状态。
  3. 服务器在tasks_set中查找任务并获取状态:
task = tasks_set.get(uuid_from_client)
if not task:
    raise TaskNotFound # send error, 404 for example
if not task.done():
    # task is not done yet
    answer_to_client('task is not done')
    return
else:
    answer_to_client('task is done. Result: ', task.result())
    tasks_set.pop(uuid_from_client)

但我还必须管理任务的超时(用户已经离开,我们应该停止他的任务)。有什么建议吗?

python-asyncio aiohttp
1个回答
1
投票

但我还必须管理任务的超时

您可以使用asyncio.wait_for为任何协同程序添加超时。代替:

# run coroutine in a new task
new_task = asyncio.create_task(coroutine(...))

您可以使用:

# run coroutine in a new task, for no longer than 10s
new_task = asyncio.create_task(asyncio.wait_for(coroutine(...), 10)

如果协程完成并且超时,new_task.done()将是真的。您可以通过测试new_task.done() and new_task.exception() is asyncio.TimeoutError来测试超时。

© www.soinside.com 2019 - 2024. All rights reserved.