搜尋
首頁後端開發Python教學Python 中使用 HTTPX 和 asyncio 的非同步 HTTP 請求

非同步程式設計在 Python 開發中變得越來越重要。 隨著 asyncio 現在成為標準庫元件和許多相容的第三方包,這種範例將繼續存在。本教學課程示範如何使用 HTTPX 程式庫進行非同步 HTTP 請求 - 非阻塞程式碼的主要用例。

什麼是非阻塞程式碼?

「非同步」、「非阻塞」和「並發」等術語可能會令人困惑。 本質上:

  • 非同步例程可以在等待結果時“暫停”,從而允許其他例程同時執行。
  • 這會創建並發執行的外觀,即使可能不涉及真正的並行性。

非同步程式碼避免阻塞,使其他程式碼能夠在等待結果時運作。 asyncio 函式庫為此提供了工具,並且 aiohttp 提供了專門的 HTTP 請求功能。 HTTP 請求非常適合非同步性,因為它們涉及等待伺服器回應,在此期間其他任務可以有效執行。

設定

確保您的 Python 環境已配置。 如果需要,請參閱虛擬環境指南(需要 Python 3.7)。 安裝HTTPX

pip install httpx==0.18.2

使用 HTTPX 發出 HTTP 請求

此範例使用對 Pokémon API 的單一 GET 請求來取得 Mew(Pokémon #151)的資料:

import asyncio
import httpx

async def main():
    url = 'https://pokeapi.co/api/v2/pokemon/151'
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        pokemon = response.json()
        print(pokemon['name'])

asyncio.run(main())

async 指定一個協程; await 產生對事件循環的控制,在結果可用時恢復執行。

提出多個請求

當發出大量請求時,非同步性的真正力量是顯而易見的。此範例取得前 150 個 Pokémon 的資料:

import asyncio
import httpx
import time

start_time = time.time()

async def main():
    async with httpx.AsyncClient() as client:
        for number in range(1, 151):
            url = f'https://pokeapi.co/api/v2/pokemon/{number}'
            response = await client.get(url)
            pokemon = response.json()
            print(pokemon['name'])

asyncio.run(main())
print(f"--- {time.time() - start_time:.2f} seconds ---")

執行的時間。 將此與同步方法進行比較。

同步請求比較

同步等效項:

import httpx
import time

start_time = time.time()
client = httpx.Client()
for number in range(1, 151):
    url = f'https://pokeapi.co/api/v2/pokemon/{number}'
    response = client.get(url)
    pokemon = response.json()
    print(pokemon['name'])

print(f"--- {time.time() - start_time:.2f} seconds ---")

注意運行時差異。 HTTPX 的連接池最大限度地減少了差異,但 asyncio 提供了進一步的最佳化。

高階非同步技術

為了獲得卓越的效能,請使用 asyncio.ensure_futureasyncio.gather 同時執行請求:

import asyncio
import httpx
import time

start_time = time.time()

async def fetch_pokemon(client, url):
    response = await client.get(url)
    return response.json()['name']

async def main():
    async with httpx.AsyncClient() as client:
        tasks = [asyncio.ensure_future(fetch_pokemon(client, f'https://pokeapi.co/api/v2/pokemon/{number}')) for number in range(1, 151)]
        pokemon_names = await asyncio.gather(*tasks)
        for name in pokemon_names:
            print(name)

asyncio.run(main())
print(f"--- {time.time() - start_time:.2f} seconds ---")

這透過並發運行請求顯著減少了執行時間。 總時間接近最長單次請求的持續時間。

結論

使用 HTTPX 和非同步程式設計可以顯著提高多個 HTTP 請求的效能。本教學提供了 asyncio 的基本介紹;進一步探索其功能以增強您的 Python 專案。 考慮探索 aiohttp 來取代非同步 HTTP 請求處理。 Asynchronous HTTP Requests in Python with HTTPX and asyncio Asynchronous HTTP Requests in Python with HTTPX and asyncio Asynchronous HTTP Requests in Python with HTTPX and asyncio

以上是Python 中使用 HTTPX 和 asyncio 的非同步 HTTP 請求的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
可以在Python數組中存儲哪些數據類型?可以在Python數組中存儲哪些數據類型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python標準庫的哪一部分是:列表或數組?Python標準庫的哪一部分是:列表或數組?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

您應該檢查腳本是否使用錯誤的Python版本執行?您應該檢查腳本是否使用錯誤的Python版本執行?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

在Python陣列上可以執行哪些常見操作?在Python陣列上可以執行哪些常見操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些類型的應用程序中,Numpy數組常用?在哪些類型的應用程序中,Numpy數組常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什麼時候選擇在Python中的列表上使用數組?您什麼時候選擇在Python中的列表上使用數組?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用