Python 3.7+:等待结果产生-API /任务系统

时间:2020-05-06 07:15:23

标签: python python-asyncio

在以下代码中,API将任务交给任务代理,任务代理将其放入队列中,然后由工作人员将其拾取。然后,工作人员将执行任务,并(通过redis消息通道)通知任务代理他已完成,然后任务代理会将其从队列中删除。这有效。 我想要的是任务代理程序然后可以将任务结果返回给API。但是我不确定如何执行此操作,因为它是异步代码,并且很难弄清楚。你能帮忙吗?

简化后的代码大致如下,但不完整。

API代码:

@router.post('', response_model=BaseDocument)
async def post_document(document: BaseDocument):
    """Create the document with a specific type and an optional name given in the payload"""
    task = DocumentTask({ <SNIP>
    })

    task_broker.give_task(task)
    result = await task_broker.get_task_result(task)
    return result

任务代理代码,第一部分是任务,第二部分是删除任务,最后一部分是我认为应该是对已删除任务的状态的阻塞调用

    def give_task(self, task_obj):
        self.add_task_to_queue(task_obj)
        <SNIP>
        self.message_channel.publish(task_obj)

    # ...
    def remove_task_from_queue(self, task):
        id_task_to_remove = task.id
        for i in range(len(task_queue)):
            if task_queue[i]["id"] == id_task_to_remove:
                removed_task = task_queue.pop(i)
                logger.debug(
                    f"[TaskBroker] Task with id '{id_task_to_remove}' succesfully removed !"
                )
                removed_task["status"] = "DONE"
                return
     # ...

       async def get_task_result(self, task):
            return task.result

我的直觉想在get_task_result中实现一种方法,该方法会阻塞task.result,直到对其进行修改为止,当我将其从队列中删除(并完成)时,我将在remove_task_from_queue中对其进行修改。

关于异步执行此操作的任何想法吗?

0 个答案:

没有答案