Skip to main content

更好用的 aiohttp 客户端,支持同步和异步使用。 性能碾压 httpx 和 requests 400%

Project description

nb_aiohttp

nb_aiohttp 是一个基于 aiohttp 的Python HTTP客户端库,旨在提供更易于使用的API和更强大的功能。它通过懒加载机制解决了 aiohttp.ClientSession 无法在模块级别实例化的问题,并同时提供了同步和异步两种请求方式。

核心特性

  • 极致性能: 底层使用 aiohttp,异步性能远超 httpx,同步性能数倍于 requests
  • 懒加载实例化: 允许在模块的全局作用域直接创建客户端实例,无需在异步函数内部进行。
  • 同步/异步双支持: 同时提供 NbAioHttpClient (异步) 和 NbSyncHttpClient (同步) 两种客户端,满足不同场景的需求。
  • 简洁的API: 提供了类似 requestsget, post 等方法,调用更直观、更简单。
  • 自动重试: 内置请求失败后的自动重试机制,增加了应用的健壮性。
  • 统一的响应对象: 封装了 NbHttpResp 对象,可以方便地获取响应状态、文本内容,并能通过 .dict 属性直接将JSON响应转换为Python字典。
  • 集成日志: 与 nb_log 无缝集成,自动记录请求错误和慢速请求,便于调试和监控。

安装

pip install nb_aiohttp

快速上手

异步用法 (NbAioHttpClient)

NbAioHttpClient 封装了 aiohttp.ClientSession,但允许你在任何地方实例化它,包括全局作用域。默认配置下,如果HTTP响应状态码表示失败(如4xx, 5xx),将会直接抛出异常。

import asyncio
from nb_aiohttp import NbAioHttpClient

# 在模块顶层直接实例化,无需在 async 函数内
http = NbAioHttpClient(timeout=10, connector_limit=100)

async def main():
    # 发起 GET 请求
    resp = await http.get('https://api.github.com/events')

    # 直接处理成功的响应
    print(f"Response Text (first 100 chars): {resp.text[:100]}")
    
    # 发起 POST 请求
    post_data = {'key': 'value'}
    resp_post = await http.post('https://httpbin.org/post', json=post_data)
    print(f"POST Response: {resp_post.dict}")

    # 使用完毕后关闭 session
    await http.close()

if __name__ == '__main__':
    asyncio.run(main())

同步用法 (NbSyncHttpClient)

NbSyncHttpClient 让你可以在同步代码中享受 aiohttp 的高性能,而无需关心 asyncio 事件循环的管理。

from nb_aiohttp import NbSyncHttpClient

# 实例化同步客户端
sync_http = NbSyncHttpClient(timeout=10)

# 在后台启动事件循环线程
sync_http.run_forever()

def main():
    # 发起 GET 请求,用法和 requests 库非常相似
    resp = sync_http.get('https://api.github.com/events')

    # 直接处理响应
    print(f"Response Text (first 100 chars): {resp.text[:100]}")

    # 发起 POST 请求
    post_data = {'key': 'value'}
    resp_post = sync_http.post('https://httpbin.org/post', json=post_data)
    print(f"POST Response: {resp_post.dict}")

if __name__ == '__main__':
    main()

与其他库的对比

性能和易用性

库 (Library) 性能 (Performance) 易用性 (Ease of Use)
NbAioHttpClient 极高 (基于aiohttp),约是 httpx 的5倍 非常简单。支持全局实例化,仅需1次await
NbSyncHttpClient ,约是 requests 的4倍 非常简单。API类似requests,无需管理事件循环。
aiohttp (原生) 极高 复杂。不能全局实例化,需要async with和多次await
httpx (异步) 较低 简单。支持全局实例化。
requests 较低 (同步阻塞) 非常简单。

(*性能数据基于在特定场景下的压测结果,仅供参考*)

代码简洁性对比

原生 aiohttp 的繁琐

需要手动管理 ClientSession 的生命周期,不能在全局实例化,导致代码冗长。

import aiohttp
import asyncio

# 必须在 async 函数内创建 session
async def fetch_with_aiohttp():
    async with aiohttp.ClientSession() as session:
        async with session.get('https://api.github.com/events') as response:
            # 2次 async with, 3次 await (包括 response.json())
            if response.status == 200:
                text = await response.text()
                print(text[:100])

NbAioHttpClient 的简洁

实现了懒加载,可以在全局实例化,API设计极大简化了调用过程。

from nb_aiohttp import NbAioHttpClient
import asyncio

# 可以在全局实例化
http = NbAioHttpClient()

async def fetch_with_nb_aiohttp():
    # 仅需 1次 await
    resp = await http.get('https://api.github.com/events')
    print(resp.text[:100])

API 参考

NbAioHttpClient

异步客户端。

  • __init__(self, *, timeout: int | float = 30, connector_limit: int = 100, max_retries: int = 3, is_raise_for_status: bool = True, **kwargs)

    • timeout: 默认请求超时时间。
    • connector_limit: TCP连接池的大小。
    • max_retries: 请求失败时的最大重试次数。
    • is_raise_for_status: 当响应状态码为4xx或5xx时,是否记录错误日志。异常总是会抛出。
    • 其他 aiohttp.ClientSession 支持的参数。
  • async def request(self, method, url, **kwargs): 发起一个HTTP请求。

  • async def get(self, url, **kwargs): 发起GET请求。

  • async def post(self, url, **kwargs): 发起POST请求。

  • async def close(self): 关闭客户端会话。

NbSyncHttpClient

同步客户端。

  • __init__(self, **kwargs): 参数与 NbAioHttpClient 相同。
  • run_forever(self): 启动后台事件循环线程。在使用任何请求方法前必须调用此方法
  • request(self, method, url, **kwargs): 发起一个同步的HTTP请求。
  • get(self, url, **kwargs): 发起同步GET请求。
  • post(self, url, **kwargs): 发起同步POST请求。

This README was generated by an AI assistant.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nb_aiohttp-1.0.tar.gz (14.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nb_aiohttp-1.0-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file nb_aiohttp-1.0.tar.gz.

File metadata

  • Download URL: nb_aiohttp-1.0.tar.gz
  • Upload date:
  • Size: 14.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.0

File hashes

Hashes for nb_aiohttp-1.0.tar.gz
Algorithm Hash digest
SHA256 6f4a3bf7e12aecb1a68fe9e9c00a817c84a0bd40aae30ab1f3db8178fc6733f2
MD5 3a9b2d6968c76d1dcba48156cd0f3630
BLAKE2b-256 395ea32133424bfc4c28697f67da5ed71c38483852df4c7451875ecaa975fab2

See more details on using hashes here.

File details

Details for the file nb_aiohttp-1.0-py3-none-any.whl.

File metadata

  • Download URL: nb_aiohttp-1.0-py3-none-any.whl
  • Upload date:
  • Size: 7.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.0

File hashes

Hashes for nb_aiohttp-1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 cc93451385f0bb030bc54224ef5b02281e6c77528e615f5da42654020aebb77f
MD5 2c19cf33121db7ccf8f856bf3d2121a9
BLAKE2b-256 4c0850b940c802967740408923616e1f829bad3701fdded0af0d8219e4d13691

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page