찾다
백엔드 개발파이썬 튜토리얼HTTPX 및 asyncio를 사용하는 Python의 비동기 HTTP 요청

비동기 프로그래밍은 Python 개발에서 점점 더 중요해지고 있습니다. 이제 asyncio가 표준 라이브러리 구성 요소와 호환되는 많은 타사 패키지로 인해 이 패러다임은 그대로 유지됩니다. 이 튜토리얼에서는 비차단 코드의 주요 사용 사례인 비동기 HTTP 요청에 HTTPX 라이브러리를 사용하는 방법을 보여줍니다.

논블로킹 코드란 무엇인가요?

'비동기', '비차단', '동시'와 같은 용어는 혼란스러울 수 있습니다. 기본적으로:

  • 비동기 루틴은 결과를 기다리는 동안 "일시 중지"하여 다른 루틴이 동시에 실행되도록 할 수 있습니다.
  • 이렇게 하면 실제 병렬 처리가 포함되지 않더라도 동시 실행처럼 보입니다.

비동기 코드는 차단을 방지하므로 결과를 기다리는 동안 다른 코드가 실행될 수 있습니다. 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마리의 포켓몬에 대한 데이터를 가져옵니다.

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 프로젝트를 향상시키기 위해 그 기능을 더욱 자세히 살펴보십시오. 대체 비동기 HTTP 요청 처리를 위해 aiohttp을 살펴보세요. 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

위 내용은 HTTPX 및 asyncio를 사용하는 Python의 비동기 HTTP 요청의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 : 편집과 해석에 대한 깊은 다이빙파이썬 : 편집과 해석에 대한 깊은 다이빙May 12, 2025 am 12:14 AM

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?May 12, 2025 am 12:09 AM

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

루프 대 파이썬의 루프 : 주요 차이점 설명루프 대 파이썬의 루프 : 주요 차이점 설명May 12, 2025 am 12:08 AM

forloopsareideal when

루프를위한 것 및 기간 : 실용 가이드루프를위한 것 및 기간 : 실용 가이드May 12, 2025 am 12:07 AM

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

파이썬 : 진정으로 해석 되었습니까? 신화를 파악합니다파이썬 : 진정으로 해석 되었습니까? 신화를 파악합니다May 12, 2025 am 12:05 AM

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

동일한 요소를 가진 Python Concatenate 목록동일한 요소를 가진 Python Concatenate 목록May 11, 2025 am 12:08 AM

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

해석 대 컴파일 언어 : Python 's Place해석 대 컴파일 언어 : Python 's PlaceMay 11, 2025 am 12:07 AM

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

루프를 위해 및 while 루프 : 파이썬에서 언제 각각을 사용합니까?루프를 위해 및 while 루프 : 파이썬에서 언제 각각을 사용합니까?May 11, 2025 am 12:05 AM

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구