简体   繁体   English

使用现有的 asyncio 事件循环在 Python 中实现 REST API

[英]Implementing REST API in Python with existing asyncio event loop

I would like to add a REST API to my application.我想向我的应用程序添加一个 REST API。 I already have some (non-REST) UNIX socket listeners using Python's asyncio which I would like to keep.我已经有一些(非 REST)UNIX 套接字侦听器使用 Python 的 asyncio,我想保留它。 Most frameworks I have found for implementing REST APIs seem to require starting their own event loop (which conflicts with asyncio's event loop).我发现的大多数用于实现 REST API 的框架似乎都需要启动它们自己的事件循环(这与 asyncio 的事件循环冲突)。

What is the best approach/library for combining REST/UNIX socket listeners without having to roll my own implementation from scratch?组合 REST/UNIX 套接字侦听器而不必从头开始实施我自己的实现的最佳方法/库是什么?

Thanks in advance!!提前致谢!!

OK, to answer my question, the above works quite nicely using aiohttp.好的,为了回答我的问题,以上使用 aiohttp 工作得很好。 For future reference, here is a minimal example adopted from the aiohttp documentation:为了将来参考,这里是从aiohttp文档中采用的一个最小示例:

import asyncio
import code
from aiohttp import web


async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)

app = web.Application()
app.router.add_get('/', handle)
app.router.add_get('/{name}', handle)

loop = asyncio.get_event_loop()
handler = app.make_handler()
f = loop.create_server(handler, '0.0.0.0', 8080)
srv = loop.run_until_complete(f)

loop.run_forever()
code.interact(local=locals())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM