aiohttp是asyncio的HTTP客户端/服务端。
特性支持HTTP客户端和HTTP服务端
开箱支持ServerWebSockets和ClientWebSockets
Web-server有中间件和可插拔路由
服务器端简单使用示例:
import asynciofrom aiohttp import web@asyncio.coroutinedef handle(request): name = request.match_info.get('name', "Anonymous") text = "Hello, " + name return web.Response(body=text.encode('utf-8'))@asyncio.coroutinedef wshandler(request): ws = web.WebSocketResponse() ws.start(request) while True: msg = yield from ws.receive() if msg.tp == web.MsgType.text: ws.send_str("Hello, {}".format(msg.data)) elif msg.tp == web.MsgType.binary: ws.send_bytes(msg.data) elif msg.tp == web.MsgType.close: break return ws@asyncio.coroutinedef init(loop): app = web.Application(loop=loop) app.router.add_route('GET', '/echo', wshandler) app.router.add_route('GET', '/{name}', handle) srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 8080) print("Server started at https://127.0.0.1:8080") return srvloop = asyncio.get_event_loop()loop.run_until_complete(init(loop))loop.run_forever()
评论