如何将参数和标头传递给 aiohttp ClientSession

She*_*ery 2 python-3.x python-requests python-asyncio aiohttp

我希望传递paramsheadersaiohttp.ClientSession如图所示这里

这是我尝试过的:

    async def make_request(self, url, headers, params):
        async with aiohttp.ClientSession(headers=headers, params=params) as session:
            async with self.limit, session.get(url=url) as response:
                await asyncio.sleep(self.rate)
                resp = await response.read()
                return resp
Run Code Online (Sandbox Code Playgroud)
async def process(url, url_id, update_id, rate, limit):
    limit = asyncio.BoundedSemaphore(limit)

    f = Fetch(
        rate=rate,
        limit=limit,
    )

    if "coinmarketcap" in url:
        params = {
            'start': '1',
            'limit': '1',
            'convert': 'USD,BTC'
        }
        headers = {
            'Accepts': 'application/json',
            'X-CMC_PRO_API_KEY': API_KEY,
        }
    else:
        params = {}
        headers = {}

    result = await f.make_request(url, headers, params)
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

Unexpected Argument at:
async with aiohttp.ClientSession(headers=headers, params=params) as session
Run Code Online (Sandbox Code Playgroud)

如果假设 url 是coinmarketcap 等,我希望设置标题no params/headers。如何解决?

Pir*_*jas 6

params 属性不能传递给会话。您需要在 get 调用中发送它,如下所示:

    async def make_request(self, url, headers, params):
        async with aiohttp.ClientSession(headers=header) as session:
            async with self.limit, session.get(url=url, params=params) as response:
                await asyncio.sleep(self.rate)
                resp = await response.read()
                return resp
Run Code Online (Sandbox Code Playgroud)

您可以在客户端会话初始化或 get 调用中发送标头。我认为两者都可以。