To handle rate-limited requests efficiently while using the threading library in Python, you can create a setup that maintains a steady pace of requests while cycling through your list of coins. We'll use a thread pool to process the requests in parallel while making sure that we don't exceed the rate limit of 45 requests per second.
Here's a Python script using the threading library which runs tasks to fetch order books for 200 coins while adhering to the rate limit:
import threading
import time
import requests
# Function to fetch order book for a single coin
def fetch_order_book(coin):
# Replace with the actual endpoint and parameters as needed
url = f'https://api.example.com/orderbook?coin={coin}'
try:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(f"Order book for {coin}: {data}")
else:
print(f"Error fetching order book for {coin}: {response.status_code}")
except Exception as e:
print(f"Exception for {coin}: {e}")
# Function to control fetching requests with rate limiting
def order_book_fetcher(coins):
for coin in coins:
# Start a new thread for the coin fetching
thread = threading.Thread(target=fetch_order_book, args=(coin,))
thread.start()
time.sleep(1 / 45) # Sleep time to maintain 45 requests per second
thread.join() # Wait for the thread to finish before proceeding to the next
def main():
# List of 200 coins (replace with actual coin symbols)
coins = [f'coin{i}' for i in range(200)]
while True: # Infinite loop to keep fetching order books
print("Fetching order books...")
order_book_fetcher(coins)
print("Cycle completed.")
time.sleep(1) # Optional: Sleep between cycles; adjust as necessary
if __name__ == "__main__":
main()
Explanation of the Code:
-
fetch_order_book Function: This function takes a coin as an argument, constructs the API URL, and performs a GET request to fetch the order books. Replace the URL with the actual endpoint you'll be querying. It handles both successful responses and errors.
-
order_book_fetcher Function: This function iterates through the list of coins, starting a new thread for each coin to fetch its order book. A time.sleep(1 / 45) call is used to space out the requests to respect the 45 requests per second limit. The thread.join() ensures we wait for the thread to finish before starting the next one, though this is not strictly necessary if you're only concerned with the overall rate limit and not the order of completion.
-
main Function: This is the main loop that will run indefinitely, fetching order books in cycles. After each complete cycle, you can adjust the time.sleep(1) to wait before starting the next cycle.
Important Notes:
- Ensure that your requests do not hit the limits set by the API service provider. Monitor usage if necessary, to make sure that you're not blocked or rate-limited by the provider.
- Replace the URL with the actual one you intend to fetch the order books from.
- Consider implementing additional error handling and logging as necessary for your use case.