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