BrianHunt
BrianHunt

Reputation: 15

Multiple aiohttp sessions

Is there a way for each URL have its own session? I read the aiohttp docs found on Github but I couldn't find if this is possible. I know it's possible with requests but unsure how to do so with aiohttp. Any help is appreciated as I haven't been able to find an answer.

sites = ['http://example.com/api/1', 'http://example.com/api/2']

async def fetch(session, site):
    print('Fetching: ' + site)

    async with session.get(site) as response:
        return await response.text()

async def main():
    t = []

    async with aiohttp.ClientSession() as session:
        for site in sites:
            task = asyncio.create_task(fetch(session, site))
            t.append(task)
        await asyncio.gather(*t)

Upvotes: 0

Views: 4035

Answers (1)

user4815162342
user4815162342

Reputation: 154906

Is there a way for each URL have its own session?

Yes, just move the session creation into the fetch coroutine:

async def fetch(site):
    print('Fetching: ' + site)

    async with aiohttp.ClientSession() as session, \
            session.get(site) as response:
        return await response.text()

async def main():
    t = []

    for site in sites:
        task = asyncio.create_task(fetch(site))
        t.append(task)
    await asyncio.gather(*t)

Upvotes: 3

Related Questions