http库三剑客:httpx

简介:httpx是Python3的一个功能齐全的HTTP客户端,它提供同步和异步API,并支持http/1.1和http/2。

帮助文档

https://www.python-httpx.org/
https://github.com/encode/httpx/

安装配置:

pip install httpx

优势:高度兼容requests库语法,支持http2.0
http库三剑客:requests

请求方式:

import httpx
result1 = httpx.get('http://httpbin.org/get')
result2 = httpx.post('http://httpbin.org/post')
result3 = httpx.put('http://httpbin.org/put')
result4 = httpx.delete('http://httpbin.org/delete')
result5 = httpx.head('http://httpbin.org/get')
result6 = httpx.options('http://httpbin.org/get')
print(result1)  # <Response [200 OK]>
print(result2)  # <Response [200 OK]>
print(result3)  # <Response [200 OK]>
print(result4)  # <Response [200 OK]>
print(result5)  # <Response [200 OK]>
print(result6)  # <Response [200 OK]>

同步调用:

import time
import httpx


def make_request(client):
    resp = client.post('https://my.ruanmei.com/Default.aspx/LoginUser', json={"username": "tom"})
    result = resp.json()
    print(result)


def main():
    session = httpx.Client()

    # 100 次调用
    for _ in range(100):
        make_request(session)


if __name__ == '__main__':
    # 开始
    start = time.time()
    main()
    # 结束
    end = time.time()
    print(f'同步:发送100次请求,耗时:{end - start}')
    # 同步:发送100次请求,耗时:9.62607216835022

异步调用:

import httpx
import asyncio
import time


async def request(client):
    resp = await client.post('https://my.ruanmei.com/Default.aspx/LoginUser', json={"username": "tom"})
    result = resp.json()
    print(result)


async def main():
    async with httpx.AsyncClient() as client:
        # # 开始
        # start = time.time()

        # 100次调用
        task_list = []
        for _ in range(100):
            req = request(client)
            task = asyncio.create_task(req)
            task_list.append(task)
        await asyncio.gather(*task_list)


if __name__ == "__main__":
    # 开始
    start = time.time()
    asyncio.run(main())
    # 结束
    end = time.time()
    print(f'异步:发送100次请求,耗时:{end - start}')
    # 异步:发送100次请求,耗时:0.7082276344299316

微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值