2016-11-15 71 views
4

我想爲我的應用程序添加一個REST API。我已經有一些(非REST)使用Python asyncio的UNIX套接字偵聽器,我想保留它。我發現的用於實現REST API的大多數框架似乎都需要啓動自己的事件循環(與asyncio的事件循環衝突)。在Python中使用現有的asyncio事件循環實現REST API

組合REST/UNIX套接字偵聽器而不必從頭開始自己實現的最佳方法/庫是什麼?

在此先感謝!

回答

4

好的,爲了回答我的問題,上面的工作很好地使用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())