我试图了解如何从 aioweb 框架内的协程处理程序运行异步进程。这是一个代码示例:
def process(request):
# this function can do some calc based on given request
# e.g. fetch/process some data and store it in DB
# but http handler don't need to wait for its completion
async def handle(request):
# process request
process(request) ### THIS SHOULD RUN ASYNCHRONOUSLY
# create response
response_data = {'status': 'ok'}
# Build JSON response
body = json.dumps(response_data).encode('utf-8')
return web.Response(body=body, content_type="application/json")
def main():
loop = asyncio.get_event_loop()
app = web.Application(loop=loop)
app.router.add_route('GET', '/', handle)
server = loop.create_server(app.make_handler(), '127.0.0.1', 8000)
print("Server started at http://127.0.0.1:8000")
loop.run_until_complete(server)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main()
我想process
从处理程序异步运行函数。有人可以提供一个我如何实现这一目标的例子。我很难理解如何在处理程序中传递/使用主事件循环并将其传递给另一个函数,该函数本身可以在其中运行异步进程。