非同期プログラミングは、Python 開発においてますます重要になっています。 現在では asyncio
が標準ライブラリ コンポーネントとなり、多くの互換性のあるサードパーティ パッケージとなっているため、このパラダイムは今後も存続します。このチュートリアルでは、非ブロッキング コードの主要な使用例である、非同期 HTTP リクエストに HTTPX
ライブラリを使用する方法を示します。
ノンブロッキング コードとは何ですか?
「非同期」、「ノンブロッキング」、「同時」などの用語は混乱を招く可能性があります。 基本的に:
- 非同期ルーチンは結果を待っている間「一時停止」でき、他のルーチンを同時に実行できます。
- これにより、真の並列処理が関与していない場合でも、同時実行のように見えます。
非同期コードはブロックを回避し、結果を待っている間に他のコードを実行できるようにします。 asyncio
ライブラリはこのためのツールを提供し、aiohttp
は特殊な HTTP リクエスト機能を提供します。 HTTP リクエストは、サーバーの応答を待機する必要があり、他のタスクを効率的に実行できる期間であるため、非同期に最適です。
セットアップ
Python 環境が構成されていることを確認してください。 必要に応じて、仮想環境ガイドを参照してください (Python 3.7 が必要です)。 HTTPX
:
pip install httpx==0.18.2
HTTPX を使用した HTTP リクエストの作成
この例では、Pokémon API への 1 つの GET リクエストを使用して、ミュウ (ポケモン #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 匹のポケモンのデータを取得します:
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 プロジェクトを強化してください。 代替の非同期 HTTP リクエスト処理については、aiohttp
を検討することを検討してください。
以上がHTTPX と asyncio を使用した Python の非同期 HTTP リクエストの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

forhandlinglaredataSetsinpython、usenumpyArrays forbetterperformance.1)numpyarraysarememory-effictientandfasterfornumericaloperations.2)nusinnnnedarytypeconversions.3)レバレッジベクトル化は、測定済みのマネージメーシェイメージーウェイズデイタイです

inpython、listsusedynamicmemoryallocation with allocation、whilenumpyArraysalocatefixedmemory.1)listsallocatemorememorythanneededededinitivative.2)numpyArrayasallocateexactmemoryforements、rededicablebutlessflexibilityを提供します。

inpython、youcanspecthedatatypeyfelemeremodelernspant.1)usenpynernrump.1)usenpynerp.dloatp.ploatm64、フォーマーpreciscontrolatatypes。

numpyisessentialfornumericalcomputinginpythonduetoitsspeed、memory efficiency、andcomprehensivematicalfunctions.1)それは、performsoperations.2)numpyArraysaremoremory-efficientthanpythonlists.3)Itofderangeofmathematicaloperty

contiguousMemoryAllocationisucial forArraysは、ForeffienceAndfastelementAccess.1)iteenablesConstantTimeAccess、O(1)、DuetodirectAddresscalculation.2)itemprovesefficiencyByAllowingMultiblementFechesperCacheLine.3)itimplifieMememm

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

Dreamweaver Mac版
ビジュアル Web 開発ツール

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

ホットトピック









