Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example showing asynchronous HTTP request with Python 3.5.0 + asyncio
import requests
import asyncio
from concurrent.futures import ThreadPoolExecutor
from timeit import default_timer
START_TIME = default_timer()
def fetch(session, csv):
base_url = ""
with session.get(base_url + csv) as response:
data = response.text
if response.status_code != 200:
elapsed = default_timer() - START_TIME
time_completed_at = "{:5.2f}s".format(elapsed)
print("{0:<30} {1:>20}".format(csv, time_completed_at))
return data
async def get_data_asynchronous():
csvs_to_fetch = [
print("{0:<30} {1:>20}".format("File", "Completed at"))
with ThreadPoolExecutor(max_workers=10) as executor:
with requests.Session() as session:
# Set any session parameters here before calling `fetch`
loop = asyncio.get_event_loop()
START_TIME = default_timer()
tasks = [
*(session, csv) # Allows us to pass in multiple arguments to `fetch`
for csv in csvs_to_fetch
for response in await asyncio.gather(*tasks):
def main():
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(get_data_asynchronous())

This comment has been minimized.

Copy link

@adityathebe adityathebe commented May 14, 2020

Is there some memory leaks in this code ?


This comment has been minimized.

Copy link
Owner Author

@tylerburdsall tylerburdsall commented May 14, 2020

There shouldn't be, if you are referring to We want to make a list of Futures (line 42) so that we can kick off each process asynchronously. We use await on line 50 when getting the results of each task.

If you do have any data to show that this leaks memory I'm happy to help pin it down!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.