▼ Click the card below to follow me
▲ Click the card above to follow me
Httpx: A Cool New Way to Make HTTP Requests in Python!
HTTP requests have always been a common requirement in Python development, and the traditional requests library has been with us for a long time. But today, I want to introduce you to a more modern and powerful HTTP client library – Httpx. It not only supports synchronous requests but also perfectly supports asynchronous requests, making it the Swiss Army knife of modern Python development!
Getting to Know Httpx: More Powerful than Requests
First, let’s take a look at how to install Httpx, which is very simple:
pip install httpx
The most basic GET request is as easy as drinking water:
import httpx
response = httpx.get('https://www.example.com')
print(response.text) # Directly print the webpage content
print(response.status_code) # Get the response status code
Asynchronous Requests: Unleashing Performance Magic
This is the killer feature of Httpx! Check out how cool asynchronous requests are:
import httpx
import asyncio
async def fetch_url(url):
async with httpx.AsyncClient() as client:
response = await client.get(url)
return response.text
async def main():
urls = [
'https://www.example1.com',
'https://www.example2.com',
'https://www.example3.com'
]
results = await asyncio.gather(*[fetch_url(url) for url in urls])
print(results)
asyncio.run(main())
Tip: Asynchronous requests can greatly improve concurrent performance, especially in scenarios where multiple web pages need to be fetched simultaneously!
Powerful Customization Capabilities
Httpx is not just about sending requests; it also supports various customizations:
import httpx
# Set request headers and timeout
client = httpx.Client(
headers={'User-Agent': 'MyAwesomeScript'},
timeout=10.0
)
# Support for proxies
proxies = {
'http://': 'http://localhost:8030',
'https://': 'http://localhost:8030'
}
client = httpx.Client(proxies=proxies)
Elegant Error Handling
No more worries about network exceptions!
import httpx
try:
response = httpx.get('https://www.example.com', timeout=3.0)
response.raise_for_status() # Automatically raise HTTP errors
except httpx.RequestError as e:
print(f"Network error: {e}")
except httpx.HTTPStatusError as e:
print(f"HTTP error: {e}")
Tip: Using raise_for_status() can automatically handle non-200 status code requests.
Practical Tips: Cookie and Session Management
Httpx’s session management is incredibly convenient:
import httpx
with httpx.Client() as client:
# Automatically manage cookies
client.post('https://login.example.com/login', data={
'username': 'user',
'password': 'pass'
})
# Subsequent requests will automatically carry the login state
response = client.get('https://example.com/dashboard')
Httpx is truly the Swiss Army knife of HTTP requests, perfectly handling both synchronous and asynchronous scenarios! I hope this article helps you open the door to a new world with Httpx~
Like and Share
Let money and love flow to you