aiohttp框架及其常用模块
[TOC] 简介 aiohttp是一个为Python提供异步HTTP 客户端/服务端编程,基于asyncio的异步库。他的核心功能如下: 同时支持客户端使用(可以理解为request的异步执行方式)和服务端使用。 同时支持服务端WebSockets组件和客户端WebSockets组件,开箱即用呦。 web服务器具有中间件,信号组件和可插拔路由的功能。 这个可插拔的路由意思就是说,你可以在代码运行的过程中增加某个接口,或者减少某个接口。 安装方式: pip install aiohttp 客户端例子: import aiohttp import asyncio import async_timeout async def fetch(session, url): with async_timeout.timeout(10): async with session.get(url) as response: return await response.text() async def main(): async with aiohttp.ClientSession() as session: html = await fetch(session, 'http://python.org') print(html) loop = asyncio.get_event_loop() loop.run_until_complete(main()) 服务端例子: 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) web.run_app(app) 常见扩展模块 模块名称 描述 aiohttp_session 处理用户会话 aiohttp-session-mongo aiomysql aiopg aioredis aiohttp_cors 解决跨域问题 aiojobs aiohttp_jinja2 aiobotocore aws文件存储服务器的异步模块 pytest-aiohttp aiohttp-swagger3 aioelasticsearch aiologstash aiokafka 更多可以去aio-libs github官方仓库查看 https://github.com/aio-libs ...