You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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 Request class is the core model for all requests. You can directly modify its properties like content (byte body), text (string body, auto-encoded), headers, method, or url before 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() (like stream, verify, timeout) have direct equivalents in httpx.AsyncClient.send().

内容的提问来源于stack exchange,提问作者stev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 19:17:33