简介: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
微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!