Python 多个aiohttp会话

Python 多个aiohttp会话,python,python-3.x,python-asyncio,aiohttp,Python,Python 3.x,Python Asyncio,Aiohttp,有没有办法让每个URL都有自己的会话?我阅读了Github上的aiohttp文档,但我找不到这是否可行。我知道请求是可能的,但不确定如何使用aiohttp。感谢您的帮助,因为我还没有找到答案 sites = ['http://example.com/api/1', 'http://example.com/api/2'] async def fetch(session, site): print('Fetching: ' + site) async with session.g

有没有办法让每个URL都有自己的会话?我阅读了Github上的aiohttp文档,但我找不到这是否可行。我知道请求是可能的,但不确定如何使用aiohttp。感谢您的帮助,因为我还没有找到答案

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)
有没有办法让每个URL都有自己的会话

是的,只需将会话创建移动到
fetch
corroutine:

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)
有没有办法让每个URL都有自己的会话

是的,只需将会话创建移动到
fetch
corroutine:

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)

@DinaTisnek如果你认为答案可以改进,请先写评论。@DinaTisnek如果你认为答案可以改进,请先写评论。