python-3.x - 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)
解决方案
推荐阅读
- java - 为什么有些元素存在但不可交互/显示?
- javascript - 如何动态定义 PWA 的起始页
- angular - 在 ag-grid 中使用 rowDrag 和 dndSource
- django - 在 CI 期间在 Django 测试数据库中启用 PSQL hstore 扩展
- android - task.getResult().exists() 总是将我传递给相同的 if 条件
- excel - 从表中查找,列位于不同的工作簿上
- c - 与 strtok 一起使用的 C 自由变量
- reactjs - 在测试反应组件和运行测试覆盖率时,这些绿色数字代表什么?
- c# - 我可以通过动作选择 Selenuim 中的元素吗?
- reactjs - 从 React 到 Web API 的 MSAL 身份验证和授权