如何使用 httpx,一个用于 Python 的 Web 客户端

用于 Python 的 httpx 包是一个出色且灵活的模块,用于与 HTTP 交互。
14 位读者喜欢这个。
Digital creative of a browser on the internet

用于 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 交互。试一试,看看它能为您做什么。

标签
Moshe sitting down, head slightly to the side. His t-shirt has Guardians of the Galaxy silhoutes against a background of sound visualization bars.
Moshe 自 1998 年以来一直参与 Linux 社区,帮助举办 Linux “安装派对”。他自 1999 年以来一直在编写 Python 程序,并为核心 Python 解释器做出了贡献。Moshe 在这些术语出现之前就一直是 DevOps/SRE,非常关心软件可靠性、构建可重复性以及其他此类事情。

评论已关闭。

© . All rights reserved.