简体   繁体   中英

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!!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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