如何将 aiohttp 与 requests_aws4auth 一起使用

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

我有同步代码,可将文件放入使用 requests_aws4auth 的 AWS 存储桶中。我想使用 aiohttp 使其异步。但是,aiohttp 似乎只能与 basicAuth 一起使用,而不能与 AWS4auth 一起使用。

有效的代码是:

    self.auth = AWS4Auth(access_key, secret_key, 'us-east-1', 's3')
    response = requests.put(
        url,
        auth = self.auth,
        data=content)

我想要类似的东西:

    async with aiohttp.ClientSession(url = url, auth=self.auth) as session:
        async with session.put(data=content) as resp:
        
            await session.close()

但是 ClientSession 想要一个 basicAuth 元组...

python python-asyncio aiohttp
1个回答
0
投票

目前,aiohttp 仅支持基本身份验证。但在 aiohttp 中,设置 auth 只会在会话标头中添加一个标头。

这是来自 aiohttp 来源的代码:

def update_auth(self, auth: Optional[BasicAuth], trust_env: bool = False) -> None:
    """Set basic auth."""
    if auth is None:
        auth = self.auth
    if auth is None and trust_env and self.url.host is not None:
        netrc_obj = netrc_from_env()
        with contextlib.suppress(LookupError):
            auth = basicauth_from_netrc(netrc_obj, self.url.host)
    if auth is None:
        return
    if not isinstance(auth, helpers.BasicAuth):
        raise TypeError("BasicAuth() tuple is required instead")
    self.headers[hdrs.AUTHORIZATION] = auth.encode()

正如您在这段代码中看到的,aiohttp 将从 auth 对象调用方法编码,然后将结果添加到标头,以 AUTHORIZATION 作为键。

因此,您可以绕过所有这些,只需自己添加标头,或者创建一个继承 AWS4Auth 的新类并添加encode() 方法。

© www.soinside.com 2019 - 2024. All rights reserved.