Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing REST API in Python with existing asyncio event loop

I would like to add a REST API to my application. I already have some (non-REST) UNIX socket listeners using Python's asyncio which I would like to keep. Most frameworks I have found for implementing REST APIs seem to require starting their own event loop (which conflicts with asyncio's event loop).

What is the best approach/library for combining REST/UNIX socket listeners without having to roll my own implementation from scratch?

Thanks in advance!!

like image 345
ws6079 Avatar asked Nov 15 '16 14:11

ws6079


1 Answers

OK, to answer my question, the above works quite nicely using aiohttp. For future reference, here is a minimal example adopted from the aiohttp documentation:

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())
like image 78
ws6079 Avatar answered Sep 24 '22 16:09

ws6079