跳转到主要内容

异步HTTP客户端/服务器框架(asyncio)

项目描述

aiohttp logo

GitHub Actions status for master branch codecov.io status for master branch Latest PyPI package version Latest Read The Docs Matrix Room — #aio-libs:matrix.org Matrix Space — #aio-libs-space:matrix.org

主要功能

  • 支持HTTP协议的客户端和服务器端。

  • 开箱即用支持客户端和服务器端Web-Sockets,避免回调地狱。

  • 为Web服务器提供中间件和可插拔路由。

入门指南

客户端

从网络上获取信息

import aiohttp
import asyncio

async def main():

    async with aiohttp.ClientSession() as session:
        async with session.get('https://pythonlang.cn') as response:

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

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

asyncio.run(main())

这将打印

Status: 200
Content-type: text/html; charset=utf-8
Body: <!doctype html> ...

来自 requests ? 阅读为什么需要这么多行 (原因).

服务器

使用简单服务器的一个示例

# examples/server_simple.py
from aiohttp import web

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)

async def wshandle(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    async for msg in ws:
        if msg.type == web.WSMsgType.text:
            await ws.send_str("Hello, {}".format(msg.data))
        elif msg.type == web.WSMsgType.binary:
            await ws.send_bytes(msg.data)
        elif msg.type == web.WSMsgType.close:
            break

    return ws


app = web.Application()
app.add_routes([web.get('/', handle),
                web.get('/echo', wshandle),
                web.get('/{name}', handle)])

if __name__ == '__main__':
    web.run_app(app)

文档

https://aiohttp.readthedocs.io/

演示

https://github.com/aio-libs/aiohttp-demos

交流渠道

aio-libs 讨论: https://github.com/aio-libs/aiohttp/discussions

Matrix: #aio-libs:matrix.org

我们支持 Stack Overflow。请在那里的问题中添加 aiohttp 标签。

要求

可选地,您可能需要安装aiodns库(出于速度考虑,强烈推荐)。

许可协议

aiohttp在Apache 2许可下提供。

Keepsafe

aiohttp社区感谢Keepsafe(https://www.getkeepsafe.com)在项目早期阶段的支持。

源代码

最新开发版本可在GitHub存储库中找到: https://github.com/aio-libs/aiohttp

基准测试

如果您对效率感兴趣,AsyncIO社区在官方wiki上维护了一个基准测试列表:https://github.com/python/asyncio/wiki/Benchmarks

支持者