Created
May 6, 2017 07:10
-
-
Save hustshawn/b7b9284f9a50fa6f93f2d5126867fa4a to your computer and use it in GitHub Desktop.
A demo to utilize asyncio to fire multiple requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import asyncio | |
import time | |
urls = [ | |
"www.baidu.com", | |
"www.sina.com", | |
"www.google.com.hk", | |
"www.sohu.com" | |
] | |
async def request(loop, url): | |
print("Sending request {}".format(url)) | |
req_start = time.time() | |
r = await loop.run_in_executor(None, requests.get, url) | |
req_end = time.time() | |
print("After the yield {0} {1}. Elapsed: {2}".format(url, r.status_code, req_end - req_start)) | |
loop = asyncio.get_event_loop() | |
tasks = [request(loop, 'http://' + url) for url in urls] | |
start_t = loop.time() | |
print("Event-Loop Time Start: {}".format(start_t)) | |
loop.run_until_complete(asyncio.wait(tasks)) | |
end_t = loop.time() | |
print("Event-Loop Time end: {}".format(end_t)) | |
print("Event-Loop Time elapsed: {}".format(end_t - start_t)) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output sample as below: