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, HEAD和OPTIONS请求都遵循相同的样式:
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)
超时又可以分为connect, read,write和pool超时。如果想详细设置,我们可以通过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 Auth和Digest Auth身份验证。要提供身份验证凭据,请将2个元组得纯文本str或bytes对象作为auth参数传递给请求函数:
response

HTTPX 是一个功能强大的 Python HTTP 客户端,支持同步和异步API,涵盖HTTP/1.1和HTTP/2。本文介绍了安装、创建请求、自定义头部、超时设置、SSL证书验证、认证、请求类型、响应处理、代理配置、异步支持等内容,详述了HTTPX在各种场景下的使用方法。
最低0.47元/天 解锁文章
113

被折叠的 条评论
为什么被折叠?



