非同步程式設計在 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_future
和 asyncio.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 請求處理。
以上是Python 中使用 HTTPX 和 asyncio 的非同步 HTTP 請求的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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

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

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

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

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

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

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

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


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

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

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3漢化版
中文版,非常好用