install:: pip3 install httpx import:: import httpx github:: encode/httpx doc:: HTTPX
用法
请求
import httpx
data = {"number": 42}
httpx.get(url)
httpx.post(url, data=data)
另一种写法:
import httpx
with httpx.Client() as client:
r = client.get("https://httpbin.org/get")
发送数据
如果同时传递 json、data、files 和 content,优先级是:
content <- files == data <- json
文件
files = {'upload-file': open('report.xls', 'rb')}
r = httpx.post("https://httpbin.org/post", files=files)
可以同时传递 data 数据:
files = {'upload-file': open('report.xls', 'rb')}
data = {'message': 'Hello, world!'}
r = httpx.post("https://httpbin.org/post", files=files, data=data)
JSON
发送 JSON 数据不需要预先使用 json 进行编码。
data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}
r = httpx.post("https://httpbin.org/post", json=data)
二进制
content = b'Hello, world'
r = httpx.post("https://httpbin.org/post", content=content)
身份验证
import httpx
# Basic 验证
httpx.get("https://example.com", auth=("my_user", "password123"))
# Digest 验证
auth = httpx.DigestAuth("my_user", "password123")
httpx.get(url, auth=auth)
DELETE 传递 JSON
需要使用 .request 函数
httpx.request(
method="DELETE",
url="https://www.example.com/",
josn={"number": 42}
)
参考:request-body-on-http-methods
响应
- .status_code: 查看编码
- .headers: 查看 Header ()
- .content: 比特
- .text: 文本
- .json(): json
- .url:查看请求的 URL