用于 Python 的 httpx
包是一个复杂的 Web 客户端。一旦安装它,您就可以使用它从网站获取数据。与往常一样,安装它的最简单方法是使用 pip
实用程序
$ python -m pip install httpx --user
要使用它,请将其导入到 Python 脚本中,然后使用 .get
函数从 Web 地址获取数据
import httpx
result = httpx.get("https://httpbin.org/get?hello=world")
result.json()["args"]
这是来自该简单脚本的输出
{'hello': 'world'}
HTTP 响应
默认情况下,httpx
不会在非 200 状态下引发错误。
尝试此代码
result = httpx.get("https://httpbin.org/status/404")
result
结果
<Response [404 NOT FOUND]>
可以显式引发响应。添加此异常处理程序
try:
result.raise_for_status()
except Exception as 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
自定义客户端
对于除了最简单的脚本之外的任何脚本,都值得使用自定义客户端。除了诸如连接池之类的良好性能改进之外,这也是配置客户端的好地方。
例如,您可以设置自定义基本 URL
client = httpx.Client(base_url="https://httpbin.org")
result = client.get("/get?source=custom-client")
result.json()["args"]
示例输出
{'source': 'custom-client'}
这对于您使用客户端与特定服务器通信的典型场景非常有用。例如,使用 base_url
和 auth
,您可以为经过身份验证的客户端构建一个很好的抽象
client = httpx.Client(
base_url="https://httpbin.org",
auth=("good_person", "secret_password"),
)
result = client.get("/basic-auth/good_person/secret_password")
result.json()
输出
{'authenticated': True, 'user': 'good_person'}
您可以将此用于构建客户端的最佳功能之一是在顶层“main”函数中构建客户端,然后将其传递。这使其他函数可以使用客户端,并使它们可以使用连接到本地 WSGI 应用程序的客户端进行单元测试。
def get_user_name(client):
result = client.get("/basic-auth/good_person/secret_password")
return result.json()["user"]
get_user_name(client)
'good_person'
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'application/json')])
return [b'{"user": "pretty_good_person"}']
fake_client = httpx.Client(app=application, base_url="https://fake-server")
get_user_name(fake_client)
输出
'pretty_good_person'
尝试 httpx
访问 python-httpx.org 以获取更多信息、文档和教程。我发现它是一个出色且灵活的模块,用于与 HTTP 交互。试一试,看看它能为您做什么。
评论已关闭。