import time import random import requests from datetime import datetime from concurrent.futures import ThreadPoolExecutor, as_completed def get_post(post_id: int) -> dict: if post_id > 100: raise ValueError("Parameter `post_id` must be less than or equal to 100") url = f"https://jsonplaceholder.typicode.com/posts/{post_id}" time_to_sleep = random.randint(1, 10) time.sleep(time_to_sleep) r = requests.get(url) r.raise_for_status() result = r.json() result["fetch_time"] = time_to_sleep del result["body"] return result if __name__ == "__main__": time_start = datetime.now() print("Starting to fetch posts...n") with ThreadPoolExecutor() as tpe: # Submit tasks and get future objects - NOW 150 POSTS IN TOTAL - 50 WILL FAIL futures = [tpe.submit(get_post, post_id) for post_id in range(1, 151)] # Process task results for future in as_completed(futures): # Your typical try/except block try: result = future.result() print(result) except Exception as e: print(f"Exception raised: {str(e)}") time_end = datetime.now() print(f"nAll posts fetched! Took: {(time_end - time_start).seconds} seconds.")