首页 > 解决方案 > python中的序列2 asyncio函数调用

问题描述

问题:当我使用 2 个不同的列表调用generateCSVFromIncidentIdsWithArgs(list)两次时,可以说“list1”和“list2”,虽然第一个列表响应正确显示,但第二个列表响应也具有 list1 的结果。我不确定在进行第二次调用之前要重置哪个变量,以便在不混合第一个列表结果的情况下显示第二个列表调用。

函数定义:函数从具有列表中提供的 ID 的 url 获取响应

   async def fetch(self, url, incident, session, csv):
        async with session.get(url) as response:
             self.format_output(incident, await response.read())


    async def bound_fetch(self, sem, url, incident, session, csv):
        # Getter function with semaphore.
        async with sem:
            await self.fetch(url, incident, session, csv)

    async def run(self, r, csv):
        url = self.conversations_url
        tasks = []
        # create instance of Semaphore
        sem = asyncio.Semaphore(1000)
        sslcontext = ssl.create_default_context(cafile=certifi.where())
        sslcontext.load_cert_chain('certificate.pem',
                           'plainkey.pem')

        # Create client session that will ensure we dont open new connection
        # per each request.
        async with ClientSession(connector=aiohttp.TCPConnector(ssl=sslcontext)) as session:
            for i in r:
                # pass Semaphore and session to every GET request
                task = asyncio.ensure_future(self.bound_fetch(sem, url + str(i), i, session, csv))
                tasks.append(task)

            responses = await asyncio.gather(*tasks)
            return responses

函数调用:

def generateCSVFromIncidentIdsWithArgs(list):
    incident_list = list
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    future = asyncio.ensure_future(run(incident_list, True))
    loop.run_until_complete(future)


generateCSVFromIncidentIdsWithArgs(list1)
generateCSVFromIncidentIdsWithArgs(list2)

标签: python-3.xasynchronoussequencepython-asyncio

解决方案


推荐阅读