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

时间:2016-11-15 14:41:43

标签: python rest sockets

我想在我的应用程序中添加REST API。我已经有一些(非REST)UNIX套接字监听器使用Python的asyncio,我想保留。我发现实现REST API的大多数框架似乎都需要启动自己的事件循环(与asyncio的事件循环冲突)。

组合REST / UNIX套接字侦听器的最佳方法/库是什么,而无需从头开始自己的实现?

提前致谢!!

1 个答案:

答案 0 :(得分:7)

好的,回答我的问题,上面使用aiohttp非常好。对于tuture参考,这是从aiohttp文档中采用的最小示例:

import asyncio
from aiohttp import web
import code

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())