httpx

 

2023-03-29

install:: pip3 install httpx

import:: import httpx

github:: encode/httpx

doc:: HTTPX


用法

请求

1
import httpx
2
3
data = {"number": 42}
4
5
httpx.get(url)
6
httpx.post(url, data=data)

另一种写法:

1
import httpx
2
3
with httpx.Client() as client:
4
r = client.get("https://httpbin.org/get")

发送数据

如果同时传递 json、data、files 和 content,优先级是:

content <- files == data <- json

文件
1
files = {'upload-file': open('report.xls', 'rb')}
2
r = httpx.post("https://httpbin.org/post", files=files)

可以同时传递 data 数据:

1
files = {'upload-file': open('report.xls', 'rb')}
2
data = {'message': 'Hello, world!'}
3
r = httpx.post("https://httpbin.org/post", files=files, data=data)
JSON

发送 JSON 数据不需要预先使用 docs/Programming/Language/Python/library/json|json 进行编码。

1
data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}
2
r = httpx.post("https://httpbin.org/post", json=data)
二进制
1
content = b'Hello, world'
2
r = httpx.post("https://httpbin.org/post", content=content)

身份验证

1
import httpx
2
3
# Basic 验证
4
httpx.get("https://example.com", auth=("my_user", "password123"))
5
6
# Digest 验证
7
auth = httpx.DigestAuth("my_user", "password123")
8
httpx.get(url, auth=auth)

DELETE 传递 JSON

需要使用 .request 函数

1
httpx.request(
2
method="DELETE",
3
url="https://www.example.com/",
4
josn={"number": 42}
5
)

参考:request-body-on-http-methods

响应

  • .status_code: 查看编码
  • .headers: 查看 Header ()
  • .content: 比特
  • .text: 文本
  • .json(): json
  • .url:查看请求的 URL