阅读(702) (1)

httpx 请求实例

2022-07-20 13:37:25 更新

为了最大程度地控制通过网络发送的内容,HTTPX 支持构建显式请求实例:

request = httpx.Request("GET", "https://example.com")

要将实例分派到网络,请创建一个Client实例并使用​ Request.send()​:

with httpx.Client() as client:
    response = client.send(request)
    ...

如果需要以默认的参数合并不支持的方式混合​client-level​和​request-level​选项,可以使用​.build_request()​,然后对​Request​实例进行任意修改。例如:

headers = {"X-Api-Key": "...", "X-Client-ID": "ABC123"}

with httpx.Client(headers=headers) as client:
    request = client.build_request("GET", "https://api.example.com")
    print(request.headers["X-Client-ID"])  # "ABC123"
    # Don't send the API key for this particular request.
    del request.headers["X-Api-Key"]
    response = client.send(request)
    ...