@geekpi
https://linux.cn/article-14353-1.html
This commit is contained in:
Xingyu Wang 2022-03-13 10:21:37 +08:00
parent 604e332bdb
commit fac4180abe

View File

@ -3,39 +3,35 @@
[#]: author: "Moshe Zadka https://opensource.com/users/moshez" [#]: author: "Moshe Zadka https://opensource.com/users/moshez"
[#]: collector: "lujun9972" [#]: collector: "lujun9972"
[#]: translator: "geekpi" [#]: translator: "geekpi"
[#]: reviewer: " " [#]: reviewer: "wxy"
[#]: publisher: " " [#]: publisher: "wxy"
[#]: url: " " [#]: url: "https://linux.cn/article-14353-1.html"
如何使用 httpx一个 Python web 客户端 httpx一个 Python Web 客户端
====== ======
Python 的 httpx 包是一个用于 HTTP 交互的一个优秀且灵活的模块。
![Digital creative of a browser on the internet][1]
Python 的 `httpx` 包是一个复杂的 web 客户端。当你安装它后,你就可以用它来从网站上获取数据。像往常一样,安装它的最简单方法是使用 `pip` 工具: > Python 的 httpx 包是一个用于 HTTP 交互的一个优秀且灵活的模块。
![](https://img.linux.net.cn/data/attachment/album/202203/13/102042hmtif0i7g3fg0ir0.jpg)
Python 的 `httpx` 包是一个复杂的 Web 客户端。当你安装它后,你就可以用它来从网站上获取数据。像往常一样,安装它的最简单方法是使用 `pip` 工具:
``` ```
`$ python -m pip install httpx --user` $ python -m pip install httpx --user
``` ```
要使用它,把它导入到 Python 脚本中,然后使用 `.get` 函数从一个 web 地址获取数据: 要使用它,把它导入到 Python 脚本中,然后使用 `.get` 函数从一个 web 地址获取数据:
``` ```
import httpx import httpx
result = httpx.get("<https://httpbin.org/get?hello=world>") result = httpx.get("https://httpbin.org/get?hello=world")
result.json()["args"] result.json()["args"]
``` ```
下面是这个简单脚本的输出: 下面是这个简单脚本的输出:
``` ```
` {'hello': 'world'}` {'hello': 'world'}
``` ```
### HTTP 响应 ### HTTP 响应
@ -44,97 +40,71 @@ result.json()["args"]
试试这个代码: 试试这个代码:
``` ```
result = httpx.get("https://httpbin.org/status/404")
result = httpx.get("<https://httpbin.org/status/404>")
result result
``` ```
结果是: 结果是:
``` ```
` <Response [404 NOT FOUND]>` <Response [404 NOT FOUND]>
``` ```
可以明确地返回一个响应。添加这个异常处理: 可以明确地返回一个响应。添加这个异常处理:
``` ```
try: try:
result.raise_for_status() result.raise_for_status()
except Exception as exc: except Exception as exc:
print("woops", exc) print("woops", exc)
``` ```
下面是结果: 下面是结果:
``` ```
woops Client error '404 NOT FOUND' for url 'https://httpbin.org/status/404'
For more information check: https://httpstatuses.com/404
woops Client error '404 NOT FOUND' for url '<https://httpbin.org/status/404>'
For more information check: <https://httpstatuses.com/404>
``` ```
### 自定义客户端 ### 自定义客户端
除了最简单的脚本之外,使用一个自定义的客户端是值得的。除了不错的性能改进,比如连接池,这是一个配置客户端的好地方。 除了最简单的脚本之外,使用一个自定义的客户端是有意义的。除了不错的性能改进,比如连接池,这是一个配置客户端的好地方。
例如, 你可以设置一个自定义的基本 URL 例如, 你可以设置一个自定义的基本 URL
``` ```
client = httpx.Client(base_url="https://httpbin.org")
client = httpx.Client(base_url="<https://httpbin.org>")
result = client.get("/get?source=custom-client") result = client.get("/get?source=custom-client")
result.json()["args"] result.json()["args"]
``` ```
输出示例: 输出示例:
``` ```
` {'source': 'custom-client'}` {'source': 'custom-client'}
``` ```
这对一个典型的场景很有用,你用客户端与一个特定的服务器对话。例如,使用 `base_url``auth`,你可以为认证的客户端建立一个漂亮的抽象: 这对用客户端与一个特定的服务器对话的典型场景很有用。例如,使用 `base_url``auth`,你可以为认证的客户端建立一个漂亮的抽象:
``` ```
client = httpx.Client( client = httpx.Client(
base_url="<https://httpbin.org>", base_url="https://httpbin.org",
auth=("good_person", "secret_password"), auth=("good_person", "secret_password"),
) )
result = client.get("/basic-auth/good_person/secret_password") result = client.get("/basic-auth/good_person/secret_password")
result.json() result.json()
``` ```
输出: 输出:
``` ```
` {'authenticated': True, 'user': 'good_person'}` {'authenticated': True, 'user': 'good_person'}
``` ```
你可以用它来做一件更好的事情,就是在顶层的 “main” 函数中构建客户端,然后把它传递给其他函数。这可以让其他函数使用客户端,并让它们与连接到本地 WSGI 应用的客户端进行单元测试。 你可以用它来做一件更棒的事情,就是在顶层的 “主” 函数中构建客户端,然后把它传递给其他函数。这可以让其他函数使用客户端,并让它们与连接到本地 WSGI 应用的客户端进行单元测试。
``` ```
def get_user_name(client): def get_user_name(client):
result = client.get("/basic-auth/good_person/secret_password") result = client.get("/basic-auth/good_person/secret_password")
return result.json()["user"] return result.json()["user"]
@ -145,16 +115,14 @@ get_user_name(client)
def application(environ, start_response): def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'application/json')]) start_response('200 OK', [('Content-Type', 'application/json')])
return [b'{"user": "pretty_good_person"}'] return [b'{"user": "pretty_good_person"}']
fake_client = httpx.Client(app=application, base_url="<https://fake-server>") fake_client = httpx.Client(app=application, base_url="https://fake-server")
get_user_name(fake_client) get_user_name(fake_client)
``` ```
输出: 输出:
``` ```
` 'pretty_good_person'` 'pretty_good_person'
``` ```
### 尝试 httpx ### 尝试 httpx
@ -168,7 +136,7 @@ via: https://opensource.com/article/22/3/python-httpx
作者:[Moshe Zadka][a] 作者:[Moshe Zadka][a]
选题:[lujun9972][b] 选题:[lujun9972][b]
译者:[geekpi](https://github.com/geekpi) 译者:[geekpi](https://github.com/geekpi)
校对:[校对者ID](https://github.com/校对者ID) 校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出