Last active
March 27, 2024 13:28
-
-
Save liamfoneill/c8e5156d8bdb270f5405bdde2c561579 to your computer and use it in GitHub Desktop.
The key aspects are: Initialize each user's rate limiter with different max requests and refill rates. Before making a request, check if there are available tokens If not, sleep based on refill time. Deduct a token for each request Refill tokens periodically based on refill rate. This allows allocating different capacity to different users while…
This file contains hidden or 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
# USAGE EXAMPLES | |
# User 1 request | |
# curl -H "X-User-ID: user1" -d "..." http://localhost:5000/charge | |
# User 2 request | |
# curl -H "X-User-ID: user2" -d "..." http://localhost:5000/charge | |
from flask import Flask, request, jsonify | |
import stripe | |
import time | |
app = Flask(__name__) | |
# Rate limiter class from previous example | |
user1_rate_limiter = RateLimiter(10, 10) | |
user2_rate_limiter = RateLimiter(5, 5) | |
@app.route('/charge', methods=['POST']) | |
def create_charge(): | |
user_id = request.headers.get('X-User-ID') | |
if user_id == 'user1': | |
rate_limiter = user1_rate_limiter | |
elif user_id == 'user2': | |
rate_limiter = user2_rate_limiter | |
else: | |
return jsonify({'error': 'Invalid user'}), 403 | |
try: | |
response = rate_limiter.make_request() | |
return jsonify(response) | |
except stripe.error.RateLimitError: | |
return jsonify({'error': 'Too many requests'}), 429 | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment