Is There A Way To Improve Speed With For Loops
I am needing to POST a series of XML elements (could be a varying amount per call). I am using Requests v2.25.1 on Python 3.9.1. While my solution works, it is taking roughly 27
Solution 1:
It looks like you are timing the elapsed time of last request in the loop. You can calculate the total elapsed time by moving r.elapsed
into the loop and summing each request, or by adding to a running total in the loop and printing at the end.
total_elapsed = 0for sgid in skillgroups:
r = requests.request("POST",icm_url, headers = icm_header,
data = body.format(agent = str(skill_id[0]), skill_urls = '<refURL>/unifiedconfig/config/skillgroup/' + str(sgid) + '</refURL>',),
verify = r"CAchain.pem",
cert = (r"cert.cer", r"cert.key"),
)
total_elapsed += r.elapsed
basic asyncio and aiohttp implementation
import asyncio
import aiohttp
asyncdefpost_request(session, url):
asyncwith session.post() as request: #add your request headers, certificate etcawait request.status
asyncdefmain():
asyncwith aiohttp.ClientSession() as session: # use client session to auto close at the end
tasks = []
for url in urls:
t = asyncio.create_task(post_request(session, url)) #create a number of tasks to run concurrently
tasks.append(t)
await asyncio.gather(*tasks) # wait for all tasks to finish before close the session
asyncio.run(main())
Post a Comment for "Is There A Way To Improve Speed With For Loops"