
- Supports both client and server side of HTTP protocol.
- Supports both client and server Web-Sockets out-of-the-box.
- Web-server has middlewares and pluggable routing.
- Python >= 3.3
- asyncio https://pypi.python.org/pypi/asyncio
aiohttp is offered under the Apache 2 license.
http://aiohttp.readthedocs.org/
The latest developer version is available in a github repository: https://github.com/KeepSafe/aiohttp
To retrieve something from the web:
importaiohttpimportasynciodefget_body(url):
response=yieldfromaiohttp.request('GET', url)
return (yieldfromresponse.read())
if__name__=='__main__':
loop=asyncio.get_event_loop()
raw_html=loop.run_until_complete(get_body('http://python.org'))
print(raw_html)You can use the get command like this anywhere in your asyncio
powered program:
response=yieldfromaiohttp.request('GET', 'http://python.org')
body=yieldfromresponse.read()
print(body)If you want to use timeouts for aiohttp client side please use standard asyncio approach:
yieldfromasyncio.wait_for(request('GET', url), 10)In aiohttp 0.12 we've added highlevel API for web HTTP server.
This is simple usage example:
importasynciofromaiohttpimportweb@asyncio.coroutinedefhandle(request):
name=request.match_info.get('name', "Anonymous")
text="Hello, "+namereturnweb.Response(body=text.encode('utf-8'))
@asyncio.coroutinedefwshandler(request):
ws=web.WebSocketResponse()
ws.start(request)
whileTrue:
msg=yieldfromws.receive()
ifmsg.tp==web.MsgType.text:
ws.send_str("Hello, {}".format(msg.data))
elifmsg.tp==web.MsgType.binary:
ws.send_bytes(msg.data)
elifmsg.tp==web.MsgType.close:
breakreturnws@asyncio.coroutinedefinit(loop):
app=web.Application(loop=loop)
app.router.add_route('GET', '/echo', wshandler)
app.router.add_route('GET', '/{name}', handle)
srv=yieldfromloop.create_server(app.make_handler(), '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
returnsrvloop=asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()