在构造请求时出现任何 aiohttps 异常时,检索带有参数的完整标头和 url

问题描述 投票:0回答:1

我想访问完整的请求数据,包括自动标头和带有查询参数的 url,而不需要这个 hacky 全局变量。在我的实际用例中,标头可以传递到会话或请求。我希望能够在请求对象初始化后出现任何异常时访问此信息(很像 requests.PreparedRequest 对象)。是否还有对 ClientRequest 的其他修改可以实现此目的?

我尝试了多种解决方案,但

TraceConfig
都没有成功。从this github issues来看,
CustomClientRequest
似乎是正确的方法。

import aiohttp
import asyncio


class CustomRequest(aiohttp.ClientRequest):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        global request_data
        request_data = {
            "headers": self.headers,
            "method": self.method,
            "url": self.url,
            "body": str(self.body),
        }


async def main():
    try:
        async with aiohttp.ClientSession(request_class=CustomRequest) as client:
            async with client.post(
                "https://badlink.io", data="a=b", params={"x": "y"}, headers={"a": "b"}
            ) as resp:
                await resp.text()
    except Exception as e:
        pass
    print(request_data)


asyncio.run(main())

结果

{
    'headers': {
        'Host': 'badlink.io',
        'a': 'b',
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate',
        'User-Agent': 'Python/3.10 aiohttp/3.9.5',
        'Content-Length': '3',
        'Content-Type': 'text/plain; charset=utf-8'
    },
    'method': 'POST',
    'url': 'https://badlink.io/?x=y',
    'body': 'a=b'
}

附注不是在寻找 aiohttps 猴子补丁。

python aiohttp
1个回答
0
投票

使用保存请求历史记录的自定义 TCPConnector 类解决。通过

ClientSession(connector=my_connector)

传递到会话
© www.soinside.com 2019 - 2024. All rights reserved.