用Flask进行异步背景处理?

2024-04-23 20:14:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个进程,我想通过http端点调用它,它将触发异步进程(几乎类似于批处理)。你知道吗

如果没有服务器功能,我的代码:

async def run(cmd):
    proc = await asyncio.create_subprocess_shell(
        cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE)

    stdout, stderr = await proc.communicate()

    print(f'[{cmd!r} exited with {proc.returncode}]')
    if stdout:
        if proc.returncode == 0:
            print(f'[stdout]\n{Fore.GREEN}{stdout.decode()}{Style.RESET_ALL}!')
        else:
            print(f'[stdout]\n{Fore.RED}{stdout.decode()}{Style.RESET_ALL}!')
    if stderr:
        print(f'[stderr]\n{Fore.RED}{stderr.decode()}{Style.RESET_ALL}!')

然后我可以通过以下方式调用子流程:

async def abar():
    await asyncio.gather(
        run('python3 --version') #literally ANY long process
       #that i need to call
    )

从那里我可以做:

asyncio.run(abar())

我的应用程序运行成功。我的目标是将asyncio.run部分放在烧瓶端点后面:

@app.route("/batch")
def e2e():
    asyncio.run(abar())
    return 'OK'

然而,这样做似乎会带来错误:

Cannot add child handler, the child watcher does not have a loop attached

通过某个http端点触发异步子进程调用的最佳方法是什么?你知道吗

我试过使用subprocess.call,但似乎不是异步的。。。你知道吗


Tags: runcmdasyncioif进程defstderrstdout
1条回答
网友
1楼 · 发布于 2024-04-23 20:14:36

我可以用subprocess.Popen来解决这个问题

而不是

async def abar():
    await asyncio.gather(
        run('python3  version') #literally ANY long process
       #that i need to call
    )

我做到了:

async def abar():
   Popen(['pyton3', ' version']) # or any long process

在实际的烧瓶路径中:

@app.route("/batch")
    def e2e():
       abar()

相关问题 更多 >