Python如何进行HTTP请求?同步和异步有什么区别?
中等Python
答题要点
# requests(同步)
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# 基本请求
response = requests.get('https://api.example.com/data')
data = response.json()
# 会话与重试
session = requests.Session()
retry = Retry(total=3, backoff_factor=0.5, status_forcelist=[500, 502, 503])
session.mount('https://', HTTPAdapter(max_retries=retry))
# httpx(同步+异步)
import httpx
# 同步
with httpx.Client(timeout=30) as client:
response = client.get('https://api.example.com/data')
# 异步
async def fetch_data():
async with httpx.AsyncClient() as client:
response = await client.get('https://api.example.com/data')
return response.json()
# 并发请求
import asyncio
async def fetch_all(urls):
async with httpx.AsyncClient() as client:
tasks = [client.get(url) for url in urls]
responses = await asyncio.gather(*tasks)
return [r.json() for r in responses]
# aiohttp(纯异步)
import aiohttp
async def fetch_with_aiohttp():
async with aiohttp.ClientSession() as session:
async with session.get('https://api.example.com/data') as response:
return await response.json()
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题