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

Management long running tasks in Aiohttp app

我在 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 已接受和任务的 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)

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

But I also have to manage timeout for tasks

您可以使用 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.

来测试超时