Pytho的HTTP交互httpx包模块使用详解

作者:Moshe 时间:2022-11-17 06:03:29 

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

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

via: https://opensource.com/article/22/3/python-httpx

来源:https://linux.cn/article-14353-1.html

标签:Pytho,HTTP,交互,httpx
0
投稿

猜你喜欢

  • 使用python实现微信小程序自动签到功能

    2021-05-30 10:04:11
  • numpy中nan_to_num的具体使用

    2021-10-31 13:04:55
  • 在页面中输出当前客户端时间javascript实例代码

    2024-02-25 23:07:56
  • 解析Golang中的GoPath和GoModule

    2024-05-09 14:56:48
  • GoLand编译带有构建标签的程序思路详解

    2024-02-18 02:13:52
  • 在Django中URL正则表达式匹配的方法

    2021-06-09 22:38:57
  • python字符串和常用数据结构知识总结

    2023-09-29 21:00:55
  • 如何取得表中字段的属性?

    2010-01-18 20:52:00
  • 用python自动生成日历

    2022-08-28 14:28:58
  • Python SVM(支持向量机)实现方法完整示例

    2021-06-09 14:20:34
  • 使用Python的turtle模块画国旗

    2021-10-22 12:31:10
  • 关于浏览器的一些观点

    2008-08-06 12:48:00
  • python 哈希表实现简单python字典代码实例

    2023-12-28 06:11:32
  • numpy给array增加维度np.newaxis的实例

    2023-06-30 06:41:34
  • css2.1实现多重背景和边框效果

    2010-06-23 19:02:00
  • python代码中怎么换行

    2023-04-07 10:46:45
  • 特征脸(Eigenface)理论基础之PCA主成分分析法

    2023-03-03 07:19:33
  • MSSQL 2005 LOG备份webshell的方法

    2024-01-16 16:43:24
  • python如何进行矩阵运算

    2021-05-01 22:58:25
  • 详解pyenv下使用python matplotlib模块的问题解决

    2023-08-08 20:25:01
  • asp之家 网络编程 m.aspxhome.com