Search code examples
python-3.xpython-requestspython-asyncioaiohttp

How to pass params and headers to aiohttp ClientSession


I wish to pass params and headers to aiohttp.ClientSession as shown here.

This is what I have tried:

    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
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)

But I am getting the error:

Unexpected Argument at:
async with aiohttp.ClientSession(headers=headers, params=params) as session

I wish to set headers if let's say the url was coinmarketcap and no params/headers otherwise. How to fix it?


Solution

  • The params attribute can't be passed to the session. You'll need to send it in the get call, like so:

        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
    

    You can send the headers in the client session initialisation or in the get call. I think either will work.