如何使用httpx AsyncClient实现请求预准备?移植requests预准备请求示例遇prepare_request方法缺失问题
How to Use httpx AsyncClient for Pre-Prepared Requests
Great question! Unlike requests, httpx doesn’t include a direct prepare_request() method, but you can replicate the pre-prepared request workflow using its core API components. Here’s how to adapt your original code to work with AsyncClient:
Step-by-Step Adaptation
First, let’s look at the equivalent async code that mirrors your requests example:
import httpx import asyncio async def main(): # Replace with your actual URL, data, and headers url = "https://example.com" data = {"key": "value"} headers = {"Content-Type": "application/x-www-form-urlencoded"} # 1. Create a raw Request object req = httpx.Request("GET", url, data=data, headers=headers) # 2. Modify the request body and headers directly # Use `content` for byte data, or `text` for string content (auto-encoded to bytes) req.content = b'Seriously, send exactly these bytes.' req.headers['Keep-Dead'] = 'parrot' # 3. Send the modified request with AsyncClient async with httpx.AsyncClient() as client: resp = await client.send( req, stream=False, verify=True, timeout=10 # Adjust timeout as needed ) print(resp.status_code) asyncio.run(main())
Key Notes for httpx Workflow
- Direct Request Manipulation: httpx’s
Requestclass is the core model for all requests. You can directly modify its properties likecontent(byte body),text(string body, auto-encoded),headers,method, orurlbefore sending. - Client-Side Request Building: If you need to apply client-level defaults (like shared headers, authentication, or proxies) to your request first, use
client.build_request()to generate a pre-configured Request object, then modify it:async with httpx.AsyncClient(headers={"X-Global-Header": "shared-value"}) as client: # Build a request with client defaults applied req = client.build_request("GET", url, data=data, headers=headers) # Modify as needed req.text = "Overridden request body text" req.headers['Keep-Dead'] = 'parrot' resp = await client.send(req) - Parameter Mapping: Most parameters you used in
requests.Session.send()(likestream,verify,timeout) have direct equivalents inhttpx.AsyncClient.send().
内容的提问来源于stack exchange,提问作者stev
相关产品推荐
相关产品推荐

