Python 3.x 如何使用aiohttp管理会话?

Python 3.x 如何使用aiohttp管理会话?,python-3.x,aiohttp,Python 3.x,Aiohttp,我正在使用aiohttp和asyncio来生成一批请求。我的第一种方法是在fetch()函数(启动asyncio.gather作业)内创建一个会话,然后将会话对象传递给执行post请求的函数(get_info) def批处理启动器(项目列表) 返回\值=循环。运行\直到\完成(获取(项目\列表)) 返回值 异步def提取(项目列表): 与aiohttp.ClientSession()作为会话异步:# def batch_starter(item_list) return_value =

我正在使用aiohttp和asyncio来生成一批请求。我的第一种方法是在fetch()函数(启动asyncio.gather作业)内创建一个会话,然后将会话对象传递给执行post请求的函数(get_info)

def批处理启动器(项目列表)
返回\值=循环。运行\直到\完成(获取(项目\列表))
返回值
异步def提取(项目列表):
与aiohttp.ClientSession()作为会话异步:#
def batch_starter(item_list)
    return_value = loop.run_until_complete(fetch(item_list))
    return return_value

async def fetch(item_list):
    async with aiohttp.ClientSession() as session:  # <- session started here
        results = await asyncio.gather(*[asyncio.ensure_future(get_info(session, item)) for item in item_list])

async def get_info(session, item):  # <- session passed to the function
    async with session.post("some_url", data={"id": item}) as resp:
        html = await resp.json()
        some_info = html.get('info')
        return some_info
import asyncio
import aiohttp
import json

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
session = aiohttp.ClientSession()  # <- session started at top of file

def batch_starter(item_list)
    return_value = loop.run_until_complete(fetch(item_list))
    return return_value

async def fetch(item_list):
    results = await asyncio.gather(*[asyncio.ensure_future(get_info(item)) for item in item_list])

async def get_info(item):
    async with session.post("some_url", data={"id": item}) as resp:  # <- session from outer scope is used
        html = await resp.json()
        some_info = html.get('info')
        return some_info