gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
Sử dụng memcache giới hạn 10 request/s theo IP trong flask
- User
Sử dụng memcache giới hạn 10 request/s theo IP trong flask
- Assistant
Để giới hạn số lượng yêu cầu tới Flask theo địa chỉ IP sử dụng memcache, bạn có thể làm như sau:
- Cài đặt memcache:
pip install python-memcached- Import
MemcachedvàFlaskvào ứng dụng Flask của bạn:
from flask import Flask import memcache- Khởi tạo memcache client trong Flask app:
app = Flask(__name__) cache = memcache.Client(['127.0.0.1:11211'], debug=0)- Định nghĩa một decorator để giới hạn số lượng yêu cầu theo IP:
from flask import request, abort from functools import wraps def limit_requests_per_ip(max_requests, time_period): def decorator(f): @wraps(f) def wrapped(*args, **kwargs): ip_address = request.remote_addr count = cache.get(ip_address) if count is None: cache.set(ip_address, 1, time_period) elif count < max_requests: cache.incr(ip_address) else: abort(429) # Trả về lỗi 429 Too Many Requests return f(*args, **kwargs) return wrapped return decorator