gpt4 book ai didi

python - aiohttp 处理程序中的后台任务

转载 作者:行者123 更新时间:2023-11-30 22:08:05 29 4
gpt4 key购买 nike

我正在尝试在 aiohttp 处理程序中启动后台长时间任务:

from aiohttp import web
import time
import asyncio


async def one(request):
print("Start")
loop = asyncio.get_event_loop()
tasks = [
asyncio.ensure_future(long_computation(1)),
asyncio.ensure_future(long_computation(2)),
]
done, _ = loop.run_until_complete(asyncio.wait(tasks))

for f in done:
print(f"{f.result()}")

return web.Response(text="one")


async def long_computation(id: int):
print(f"run long computation with delay: {id}")
time.sleep(id)
print(f"done long computation with delay: {id}")


app = web.Application(client_max_size=1024 * 1024 * 10)
app.add_routes([web.get('/one', one)])

web.run_app(app)

但出现错误:

Error handling request
Traceback (most recent call last):
File "env/lib/python3.6/site-packages/aiohttp/web_protocol.py", line 378, in start
resp = await self._request_handler(request)
File "env/lib/python3.6/site-packages/aiohttp/web_app.py", line 341, in _handle
resp = await handler(request)
File "test_async.py", line 13, in one
done, _ = loop.run_until_complete(asyncio.wait(tasks))
File "/usr/lib/python3.6/asyncio/base_events.py", line 455, in run_until_complete
self.run_forever()
File "/usr/lib/python3.6/asyncio/base_events.py", line 409, in run_forever
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
run long computation with delay: 1
done long computation with delay: 1
run long computation with delay: 2
done long computation with delay: 2

我错过了什么?

最佳答案

您需要更换:

done, _ = loop.run_until_complete(asyncio.wait(tasks))

与:

done, _ = await asyncio.wait(tasks)

此外,如果 long_computation 阻塞,您需要使用 run_in_executor 将其移交给单独的线程。 :

loop = asyncio.get_event_loop()
tasks = [
loop.run_in_executor(None, long_computation, 1),
loop.run_in_executor(None, long_computation, 2),
]

关于python - aiohttp 处理程序中的后台任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52276565/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com