Python-http请求

复制代码
# -*- coding: utf-8 -*-

import time
import requests
import httpx
import aiohttp
import asyncio


url = 'https://www.baidu.com/'


# ##################################### 时间装饰器 ###################################################


def wrapper(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        res = func(*args, **kwargs)
        print(time.time() - start_time)
        return res
    return inner

# ##################################### 同步请求 ###################################################


@wrapper
def requests_sync_test(count=100):
    session = requests.Session()
    for _ in range(count):
        res = session.get(url=url)
        print(res.json())


@wrapper
def http_x_sync_test(count=100):
    for _ in range(count):
        res = httpx.get(url=url)
        print(res.json())


# ##################################### 异步请求 ###################################################


async def request(client):
    resp = await client.get(url=url)
    result = resp.json()
    print(result)


@wrapper
async def http_x_async_test(count=100):
    async with httpx.AsyncClient() as client:
        task_list = []
        for _ in range(count):
            task = asyncio.create_task(
                request(client=client)
            )
            task_list.append(task)
        await asyncio.gather(*task_list)


@wrapper
async def aio_http_async_text(count=100):
    """废弃|太慢"""
    async with aiohttp.ClientSession() as client:
        for _ in range(count):
            res = await client.get(url=url)
            res_json = await res.json()
            print(res_json)


if __name__ == '__main__':
    requests_sync_test(count=10)
    # asyncio.run(http_x_async_test(10))
    # asyncio.run(aio_http_async_text(10))
复制代码

参考:https://www.pythonf.cn/read/36407

posted @   一石数字欠我15w!!!  阅读(201)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
点击右上角即可分享
微信分享提示