【发布时间】:2021-02-23 12:23:00
【问题描述】:
我对 aiohttp 和 asyncio 非常陌生,因此对我的无知表示歉意。我在文档的事件循环部分遇到了困难,并且不认为我下面的代码是异步执行的。我正在尝试通过itertools 获取两个列表的所有组合的输出,并将 POST 发送到 XML。使用requests 模块时列出了更完整的版本here,但这并不理想,因为我可能需要一次发布1000+ 个请求。下面是它现在的样子:
import aiohttp
import asyncio
import itertools
skillid = ['7715','7735','7736','7737','7738','7739','7740','7741','7742','7743','7744','7745','7746','7747','7748' ,'7749','7750','7751','7752','7753','7754','7755','7756','7757','7758','7759','7760','7761','7762','7763','7764','7765','7766','7767','7768','7769','7770','7771','7772','7773','7774','7775','7776','7777','7778','7779','7780','7781','7782','7783','7784']
agent= ['5124','5315','5331','5764','6049','6076','6192','6323','6669','7690','7716']
url = 'https://url'
user = 'user'
password = 'pass'
headers = {
'Content-Type': 'application/xml'
}
async def main():
async with aiohttp.ClientSession() as session:
for x in itertools.product(agent,skillid):
payload = "<operation><operationType>update</operationType><refURLs><refURL>/unifiedconfig/config/agent/" + x[0] + "</refURL></refURLs><changeSet><agent><skillGroupsRemoved><skillGroup><refURL>/unifiedconfig/config/skillgroup/" + x[1] + "</refURL></skillGroup></skillGroupsRemoved></agent></changeSet></operation>"
async with session.post(url,auth=aiohttp.BasicAuth(user, password), data=payload,headers=headers) as resp:
print(resp.status)
print(await resp.text())
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
我看到可以使用协程,但不确定是否适用,因为只有一个任务要执行。任何澄清表示赞赏。
【问题讨论】: