python-httpx的使用

HTTPX 是一个功能强大的 Python HTTP 客户端,支持同步和异步API,涵盖HTTP/1.1和HTTP/2。本文介绍了安装、创建请求、自定义头部、超时设置、SSL证书验证、认证、请求类型、响应处理、代理配置、异步支持等内容,详述了HTTPX在各种场景下的使用方法。
摘要由CSDN通过智能技术生成

HTTPX是Python3的功能齐全的HTTP客户端,它提供同步和异步API,并支持HTTP/1.1和HTTP/2

安装

pip install httpx

创建请求

通过httpx库发出一个请求非常简单,如下:

import httpx

response = httpx.get('https://www.baidu.com/')
print(type(response), response)     # <class 'httpx.Response'> <Response [200 OK]>

同样,我们再来发出一个POST请求:

response = httpx.post('http://localhost:5000/login', data={'username': 'httpx', 'password': '123456'})

PUT, DELETE, HEADOPTIONS请求都遵循相同的样式:

response = httpx.put('http://www.baidu.com/', data={key: value})
response = httpx.head('http://www.baidu.com/')
response = httpx.delete('http://www.baidu.com/')
response = httpx.options('http://www.baidu.com/')

自定义头部

要在传入请求中包含其他标头,请使用headers关键字参数:

header = {"user-agent": 'my_test/0001'}
response = httpx.get("https://api.github.com/events", headers=header)

超时时间

httpx设置默认的超时时间为5秒,超过此时间未响应将引发错误。我们可以通过timeout关键字参数来手动修改它:

response = httpx.get('http://localhost:5000/update', timeout=10)

你也可以将其设置为None完全禁用超时行为

response = httpx.get('http://localhost:5000/update', timeout=None)

超时又可以分为connectreadwritepool超时。如果想详细设置,我们可以通过httpx.Timeout类来实现:

# 读取超时为10s,其他超时为5秒
timeout = httpx.Timeout(5, read=10)
response = httpx.get('http://localhost:5000/update', timeout=timeout)

SSL证书

通过httpx发出HTTPS请求时,需要验证所请求主机的身份。我们可以通过verify来指定我们存在的CA证书:

response = httpx.get('https://example.org', verify='../../client.pem')

或者你可以传递标准库ssl.SSLContext

import ssl
import httpx

context = ssl.create_default_context()
context.load_verify_locations(cafile='../../client.pem')
response = httpx.get('https://example.org', verify='../../client.pem')

又或者,你可以将verify设置为False禁用SSL验证:

response = httpx.get('https://example.org', verify=False)

认证

HTTPX支持Basic AuthDigest Auth身份验证。要提供身份验证凭据,请将2个元组得纯文本strbytes对象作为auth参数传递给请求函数:

response
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>