首页 > 文章列表 > httpx:一个 Python Web 客户端

httpx:一个 Python Web 客户端

Python httpx
109 2023-05-03

httpx:一个 Python Web 客户端

Python 的 ​​httpx​​ 包是一个复杂的 Web 客户端。当你安装它后,你就可以用它来从网站上获取数据。像往常一样,安装它的最简单方法是使用 ​​pip​​ 工具:

​.get​​ 函数从一个 web 地址获取数据:import httpx
result = httpx.get("https://httpbin.org/get?hello=world")
result.json()["args"]

下面是这个简单脚本的输出:

​httpx​​ 不会在非 200 状态下引发错误。试试这个代码:result = httpx.get("https://httpbin.org/status/404")
result

结果是:

​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'}

你可以用它来做一件更棒的事情,就是在顶层的 “主” 函数中构建客户端,然后把它传递给其他函数。这可以让其他函数使用客户端,并让它们与连接到本地 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 交互的优秀而灵活的模块。试一试,看看它能为你做什么。