Skip to content

请求兼容性指南

¥Requests Compatibility Guide

HTTPX 旨在与requestsAPI,尽管在某些地方存在一些设计差异。

¥HTTPX aims to be broadly compatible with the requests API, although there are a few design differences in places.

本文档概述了 API 不同的地方......

¥This documentation outlines places where the API differs...

重定向

¥Redirects

不像requests,HTTPX 确实默认不遵循重定向

¥Unlike requests, HTTPX does not follow redirects by default.

我们在这里的行为有所不同因为自动重定向可以轻松掩盖不必要的网络调用

¥We differ in behaviour here because auto-redirects can easily mask unnecessary network calls being made.

您仍然可以启用行为来自动遵循重定向,但您需要明确地这样做......

¥You can still enable behaviour to automatically follow redirects, but you need to do so explicitly...

response = client.get(url, follow_redirects=True)

或者实例化一个客户端,默认启用重定向...

¥Or else instantiate a client, with redirect following enabled by default...

client = httpx.Client(follow_redirects=True)

客户端实例

¥Client instances

HTTPX 等效于requests.Sessionhttpx.Client

¥The HTTPX equivalent of requests.Session is httpx.Client.

session = requests.Session(**kwargs)

通常等同于

¥is generally equivalent to

client = httpx.Client(**kwargs)

请求 URL

¥Request URLs

访问response.url将返回URL实例,而不是字符串。

¥Accessing response.url will return a URL instance, rather than a string.

使用str(response.url)如果您需要一个字符串实例。

¥Use str(response.url) if you need a string instance.

确定下一个重定向请求

¥Determining the next redirect request

requests库公开一个属性response.next,可用于获取下一个重定向请求。

¥The requests library exposes an attribute response.next, which can be used to obtain the next redirect request.

session = requests.Session()
request = requests.Request("GET", ...).prepare()
while request is not None:
    response = session.send(request, allow_redirects=False)
    request = response.next

在 HTTPX 中,该属性被命名为response.next_request。 例如:

¥In HTTPX, this attribute is instead named response.next_request. For example:

client = httpx.Client()
request = client.build_request("GET", ...)
while request is not None:
    response = client.send(request)
    request = response.next_request

请求内容

¥Request Content

对于上传原始文本或二进制内容,我们更喜欢使用content参数,以便更好地将这种用法与上传表单数据的情况区分开。

¥For uploading raw text or binary content we prefer to use a content parameter, in order to better separate this usage from the case of uploading form data.

例如,使用content=...上传原始内容:

¥For example, using content=... to upload raw content:

# Uploading text, bytes, or a bytes iterator.
httpx.post(..., content=b"Hello, world")

并使用data=...发送表单数据:

¥And using data=... to send form data:

# Uploading form data.
httpx.post(..., data={"message": "Hello, world"})

使用data=<text/byte content>将引发弃用警告,预计将随着 HTTPX 1.0 的发布而被完全删除。

¥Using the data=<text/byte content> will raise a deprecation warning, and is expected to be fully removed with the HTTPX 1.0 release.

上传文件

¥Upload files

HTTPX 严格强制上传文件必须以二进制模式打开,以避免尝试上传以文本模式打开的文件时导致的字符编码问题。

¥HTTPX strictly enforces that upload files must be opened in binary mode, in order to avoid character encoding issues that can result from attempting to upload files opened in text mode.

内容编码

¥Content encoding

HTTPX 使用utf-8用于编码str请求主体。例如,当使用content=<str>请求主体将被编码为utf-8在通过网络发送之前。这与使用latin1如果需要显式编码,请显式传递编码字节,例如content=<str>.encode("latin1")对于响应主体,假设服务器未发送显式编码,则 HTTPX 将尽力找出合适的编码。HTTPX 会猜测用于解码响应的编码,使用charset_normalizer。回退到该值或任何少于 32 个八位字节的内容将使用utf-8error="replace"解码器策略。

¥HTTPX uses utf-8 for encoding str request bodies. For example, when using content=<str> the request body will be encoded to utf-8 before being sent over the wire. This differs from Requests which uses latin1. If you need an explicit encoding, pass encoded bytes explicitly, e.g. content=<str>.encode("latin1"). For response bodies, assuming the server didn't send an explicit encoding then HTTPX will do its best to figure out an appropriate encoding. HTTPX makes a guess at the encoding to use for decoding the response using charset_normalizer. Fallback to that or any content with less than 32 octets will be decoded using utf-8 with the error="replace" decoder strategy.

曲奇饼

¥Cookies

如果使用客户端实例,则应始终在客户端上设置 cookie,而不是根据每个请求设置。

¥If using a client instance, then cookies should always be set on the client rather than on a per-request basis.

支持这种用法:

¥This usage is supported:

client = httpx.Client(cookies=...)
client.post(...)

这种用法是不是支持:

¥This usage is not supported:

client = httpx.Client()
client.post(..., cookies=...)

我们倾向于在这里强制执行更严格的 API,因为它对 cookie 持久性提供了更清晰的期望,特别是在发生重定向时。

¥We prefer enforcing a stricter API here because it provides clearer expectations around cookie persistence, particularly when redirects occur.

状态代码

¥Status Codes

在我们的文档中,我们更喜欢使用大写版本,例如codes.NOT_FOUND,但也提供小写版本以实现 API 兼容性requests

¥In our documentation we prefer the uppercased versions, such as codes.NOT_FOUND, but also provide lower-cased versions for API compatibility with requests.

请求包含 HTTPX 不支持的状态代码的各种同义词。

¥Requests includes various synonyms for status codes that HTTPX does not support.

流式响应

¥Streaming responses

HTTPX 提供了.stream()接口而不是使用stream=True。这确保了流式响应始终在流块之外正确关闭,并且使得在哪些点可以使用流式 I/O API 进行响应更加直观。

¥HTTPX provides a .stream() interface rather than using stream=True. This ensures that streaming responses are always properly closed outside of the stream block, and makes it visually clearer at which points streaming I/O APIs may be used with a response.

例如:

¥For example:

with httpx.stream("GET", "https://www.example.com") as response:
    ...

stream()块请求数据可通过以下方式获得:

¥Within a stream() block request data is made available with:

  • .iter_bytes()- 而不是response.iter_content()

    ¥.iter_bytes() - Instead of response.iter_content()

  • .iter_text()- 而不是response.iter_content(decode_unicode=True)

    ¥.iter_text() - Instead of response.iter_content(decode_unicode=True)

  • .iter_lines()- 对应于response.iter_lines()

    ¥.iter_lines() - Corresponding to response.iter_lines()

  • .iter_raw()- 使用这个代替response.raw

    ¥.iter_raw() - Use this instead of response.raw

  • .read()- 阅读整个回复正文,确保response.textresponse.content可用的。

    ¥.read() - Read the entire response body, making response.text and response.content available.

超时

¥Timeouts

HTTPX 默认包含合理的超时对于所有网络操作,而请求默认没有超时。

¥HTTPX defaults to including reasonable timeouts for all network operations, while Requests has no timeouts by default.

要获得与请求相同的行为,请设置timeout参数None

¥To get the same behavior as Requests, set the timeout parameter to None:

httpx.get('https://www.example.com', timeout=None)

代理密钥

¥Proxy keys

HTTPX 使用 mounts 参数进行 HTTP 代理和传输路由。它的功能远不止代理,还允许您配置代理路由以外的更多内容。更多详细文档,请参阅安装运输

¥HTTPX uses the mounts argument for HTTP proxying and transport routing. It can do much more than proxies and allows you to configure more than just the proxy route. For more detailed documentation, see Mounting Transports.

使用时httpx.Client(mounts={...})为了映射到不同的传输方式,我们使用完整的 URL 方案,例如mounts={"http://": ..., "https://": ...}

¥When using httpx.Client(mounts={...}) to map to a selection of different transports, we use full URL schemes, such as mounts={"http://": ..., "https://": ...}.

这与requests使用proxies={"http": ..., "https": ...}

¥This is different to the requests usage of proxies={"http": ..., "https": ...}.

此更改是为了与更复杂的映射更好地保持一致,其中可能还包括域名,例如mounts={"all://": ..., httpx.HTTPTransport(proxy="all://www.example.com": None})它将全部请求映射到代理上,除了对“www.example.com”的请求有明确的排除。

¥This change is for better consistency with more complex mappings, that might also include domain names, such as mounts={"all://": ..., httpx.HTTPTransport(proxy="all://www.example.com": None}) which maps all requests onto a proxy, except for requests to "www.example.com" which have an explicit exclusion.

另请注意requests.Session.request(...)允许proxies=...参数,而httpx.Client.request(...)不允许mounts=...

¥Also note that requests.Session.request(...) allows a proxies=... parameter, whereas httpx.Client.request(...) does not allow mounts=....

SSL 配置

¥SSL configuration

当使用Client例如,ssl 配置应始终在客户端实例化时传递,而不是传递给请求方法。

¥When using a Client instance, the ssl configurations should always be passed on client instantiation, rather than passed to the request method.

如果需要多个不同的 SSL 配置,则应该对每个 SSL 配置使用不同的客户端实例。

¥If you need more than one different SSL configuration, you should use different client instances for each SSL configuration.

HTTP 方法的请求主体

¥Request body on HTTP methods

HTTPGETDELETEHEAD, 和OPTIONS方法被指定为不支持请求主体。为了与此保持一致,.get.delete.head.options功能不支持contentfilesdata, 或者json參數。

¥The HTTP GET, DELETE, HEAD, and OPTIONS methods are specified as not supporting a request body. To stay in line with this, the .get, .delete, .head and .options functions do not support content, files, data, or json arguments.

如果你确实需要使用这些 http 方法发送请求数据,你应该使用通用.request函数来代替。

¥If you really do need to send request data using these http methods you should use the generic .request function instead.

httpx.request(
  method="DELETE",
  url="https://www.example.com/",
  content=b'A request body on a DELETE request.'
)

检查成功和失败响应

¥Checking for success and failure responses

我们不支持response.is_ok因为那里的命名含糊不清,可能会错误地暗示等同于response.status_code == codes.OK。相反,我们提供response.is_success属性,可用于检查 2xx 响应。

¥We don't support response.is_ok since the naming is ambiguous there, and might incorrectly imply an equivalence to response.status_code == codes.OK. Instead we provide the response.is_success property, which can be used to check for a 2xx response.

请求实例

¥Request instantiation

没有准备好的请求在 HTTPX 中。如果需要自定义请求实例,请参阅请求实例

¥There is no notion of prepared requests in HTTPX. If you need to customize request instantiation, see Request instances.

除了,httpx.Request()不支持authtimeoutfollow_redirectsmountsverifycert参数。然而,这些httpx.requesthttpx.gethttpx.post等等,以及Client实例

¥Besides, httpx.Request() does not support the auth, timeout, follow_redirects, mounts, verify and cert parameters. However these are available in httpx.request, httpx.get, httpx.post etc., as well as on Client instances.

嘲讽

¥Mocking

如果你需要像测试实用程序一样模拟 HTTPXresponsesrequests-mock对于requests, 看RESPX

¥If you need to mock HTTPX the same way that test utilities like responses and requests-mock does for requests, see RESPX.

缓存

¥Caching

如果你使用cachecontrol或者requests-cache添加 HTTP 缓存支持requests库,您可以使用希舍尔用于 HTTPX。

¥If you use cachecontrol or requests-cache to add HTTP Caching support to the requests library, you can use Hishel for HTTPX.

网络层

¥Networking layer

requests将其大部分 HTTP 网络代码推迟到优秀的urllib3图书馆

¥requests defers most of its HTTP networking code to the excellent urllib3 library.

另一方面,HTTPX 使用HTTP核心作为其核心 HTTP 网络层,这是一个不同于urllib3

¥On the other hand, HTTPX uses HTTPCore as its core HTTP networking layer, which is a different project than urllib3.

查询参数

¥Query Parameters

requests省略params其价值观是None(例如requests.get(..., params={"foo": None}))。HTTPX 不支持此功能。

¥requests omits params whose values are None (e.g. requests.get(..., params={"foo": None})). This is not supported by HTTPX.

对于两个查询参数(params=) 和表单数据 (data=),requests支持发送元组列表(例如requests.get(..., params=[('key1', 'value1'), ('key1', 'value2')]))。HTTPX 不支持此功能。请使用以列表为值的字典。例如:httpx.get(..., params={'key1': ['value1', 'value2']})或使用表单数据:httpx.post(..., data={'key1': ['value1', 'value2']})

¥For both query params (params=) and form data (data=), requests supports sending a list of tuples (e.g. requests.get(..., params=[('key1', 'value1'), ('key1', 'value2')])). This is not supported by HTTPX. Instead, use a dictionary with lists as values. E.g.: httpx.get(..., params={'key1': ['value1', 'value2']}) or with form data: httpx.post(..., data={'key1': ['value1', 'value2']}).

事件挂钩

¥Event Hooks

requests允许事件钩子发生变异RequestResponse对象。请参阅示例在文档中给出requests

¥requests allows event hooks to mutate Request and Response objects. See examples given in the documentation for requests.

在 HTTPX 中,事件钩子可以访问请求和响应的属性,但事件钩子回调不能改变原始请求/响应。

¥In HTTPX, event hooks may access properties of requests and responses, but event hook callbacks cannot mutate the original request/response.

如果您希望获得更多控制权,请考虑查看定制运输

¥If you are looking for more control, consider checking out Custom Transports.