日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Pytho的HTTP交互httpx包模塊使用詳解_python

作者:Moshe?Zadka ? 更新時間: 2022-05-24 編程語言

Python 的?httpx?包是一個復(fù)雜的 Web 客戶端。當你安裝它后,你就可以用它來從網(wǎng)站上獲取數(shù)據(jù)。像往常一樣,安裝它的最簡單方法是使用?pip?工具:

$ python -m pip install httpx --user

要使用它,把它導(dǎo)入到 Python 腳本中,然后使用?.get?函數(shù)從一個 web 地址獲取數(shù)據(jù):

import httpx
result = httpx.get("https://httpbin.org/get?hello=world")
result.json()["args"]

下面是這個簡單腳本的輸出:

{'hello': 'world'}

HTTP 響應(yīng)

默認情況下,httpx?不會在非 200 狀態(tài)下引發(fā)錯誤。

試試這個代碼:

result = httpx.get("https://httpbin.org/status/404")
result

結(jié)果是:

可以明確地返回一個響應(yīng)。添加這個異常處理:

try:
    result.raise_for_status()
except Exception as exc:
    print("woops", exc)

下面是結(jié)果:

woops Client error '404 NOT FOUND' for url 'https://httpbin.org/status/404'

For more information check: https://httpstatuses.com/404

自定義客戶端

除了最簡單的腳本之外,使用一個自定義的客戶端是有意義的。除了不錯的性能改進,比如連接池,這也是一個配置客戶端的好地方。

例如, 你可以設(shè)置一個自定義的基本 URL:

client = httpx.Client(base_url="https://httpbin.org")
result = client.get("/get?source=custom-client")
result.json()["args"]

輸出示例:

{'source': 'custom-client'}

這對用客戶端與一個特定的服務(wù)器對話的典型場景很有用。例如,使用?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'}

你可以用它來做一件更棒的事情,就是在頂層的 “主” 函數(shù)中構(gòu)建客戶端,然后把它傳遞給其他函數(shù)。這可以讓其他函數(shù)使用客戶端,并讓它們與連接到本地 WSGI 應(yīng)用的客戶端進行單元測試。

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?了解更多信息、文檔和教程。我發(fā)現(xiàn)它是一個與 HTTP 交互的優(yōu)秀而靈活的模塊。試一試,看看它能為你做什么。

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

原文鏈接:https://linux.cn/article-14353-1.html

欄目分類
最近更新