目 录CONTENT

文章目录

Python:asyncio库构建的开源框架之AIOHTTP

Administrator
2025-10-23 / 0 评论 / 0 点赞 / 0 阅读 / 0 字

 

字数 790,阅读大约需 4 分钟

Python:asyncio库构建的开源框架之AIOHTTP


aiohttp是一个基于Python的asyncio库构建的开源框架,它提供了异步的HTTP客户端和服务器功能,用于构建高性能的Web应用程序。 它利用Python的async/await语法实现非阻塞I/O,能够同时处理大量并发请求,尤其适合需要高吞吐量和高并发的网络场景,如实时聊天或大规模数据爬取。
在实际开发过程中:高并发和异步处理,是经常出现的要求,在python里,有async异步库。在此基础上,开源框架aiohttp提供了现成的异步客户端和服务器,用于构建更好的web程序,因此值得学习和使用。
最好是在实际开发过程中,阅读官方文档和参考示例,并结合自己的业务代码,进行编程开发。官方地址:GitHub - aio-libs/aiohttp: Asynchronous HTTP client/server framework for asyncio and Python[1]

介绍aiohttp

aiohttp 的官方地址是:https://docs.aiohttp.org/

  1. 1. 异步 Web 服务器:aiohttp 可以作为异步 Web 服务器,处理并发请求,支持WebSocket 和 HTTP/2 协议

  2. 2. 异步 HTTP 客户端:aiohttp 提供了一个高性能的异步HTTP客户端,用于向其他服务器发出异步请求

  3. 3. 轻量级:aiohttp 的设计简单,代码量较少,易于理解和维护。

  4. 4. 内置WebSocket支持:aiohttp 内置了对WebSocket的支持,可以轻松地实现实时双向通信。

  5. 5. 兼容性:aiohttp 兼容 Python 3.5+ 版本,并且可以与其他异步库和框架无缝集成。

请记住

aiohttp 建立在 Python 的 asyncio 之上,利用事件循环(Event Loop)实现非阻塞 I/O 操作:

  1. 1. 协程(Coroutine):使用 async/await 语法

  2. 2. 事件循环:管理所有异步任务的调度

  3. 3. 非阻塞 I/O:等待网络响应时可以处理其他任务

为什么要学习aiohttp

为什么用 aiohttp? : r/learnpython[2]

  1. 1. 微服务架构:服务间频繁通信

  2. 2. 实时应用:聊天、通知、直播

  3. 3. 数据聚合:同时调用多个 API

  4. 4. 高并发服务:支持数千并发连接

安装部署

命令:pip install aiohttp

客户端

基本请求


    
    
    
  import aiohttp
import asyncio
async def main():

    async with aiohttp.ClientSession() as session:
        async with session.get('http://python.org') as response:

            print("Status:", response.status)
            print("Content-type:", response.headers['content-type'])

            html = await response.text()
            print("Body:", html[:15], "...")

asyncio.run(main())

并发请求


    
    
    
  async def fetch_multiple():
    urls = [
        'https://api.github.com',
        'https://www.python.org',
        'https://httpbin.org/get'
    ]
    
    async with aiohttp.ClientSession() as session:
        tasks = [session.get(url) for url in urls]
        responses = await asyncio.gather(*tasks)
        
        for response in responses:
            print(f"{response.url}: {response.status}")
            await response.text()  # 读取内容

asyncio.run(fetch_multiple())

流失下载


    
    
    
  async def download_file(url, filename):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            with open(filename, 'wb') as f:
                async for chunk in response.content.iter_chunked(8192):
                    f.write(chunk)

服务端

服务器示例


    
    
    
  from aiohttp import web

async def handle_hello(request):
    name = request.match_info.get('name', 'World')
    return web.Response(text=f"Hello, {name}!")

async def handle_json(request):
    data = await request.json()
    return web.json_response({'received': data})

app = web.Application()
app.add_routes([
    web.get('/', handle_hello),
    web.get('/hello/{name}', handle_hello),
    web.post('/api/data', handle_json)
])

if __name__ == '__main__':
    web.run_app(app, host='127.0.0.1', port=8080)

websocket


    
    
    
  async def websocket_handler(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    
    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            await ws.send_str(f"Echo: {msg.data}")
        elif msg.type == aiohttp.WSMsgType.ERROR:
            print(f'Error: {ws.exception()}')
    
    return ws

app.add_routes([web.get('/ws', websocket_handler)])

引用链接

[1] GitHub - aio-libs/aiohttp: Asynchronous HTTP client/server framework for asyncio and Python: https://github.com/aio-libs/aiohttp
[2] 为什么用 aiohttp? : r/learnpython: https://www.reddit.com/r/learnpython/comments/5rl10t/why_aiohttp/?tl=zh-hans

 

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区