应用层速率限制的django框架
django-throttle-requests的Python项目详细描述
为django项目实现特定于应用程序的速率限制中间件的框架
本模块的目的是:
实现应用程序级(或略低于)速率限制规则。通常,这些规则会表示为“在定义的时间段内的最大请求”。例如:
- IP地址每天最多可发出1500个请求
- 具有OAuth访问令牌的用户可以进行500次读取/小时和200次写入/小时
不适用于:
令牌桶或泄漏桶过滤器:主要用于流量整形,这些算法由防火墙和服务器(如nginx)实现。
安装
使用pip安装库:
sudo pip install django-throttle-requests
将目录throttle添加到项目的PYTHONPATH中。
在项目设置中插入以下配置:
THROTTLE_ZONES = { 'default': { 'VARY':'throttle.zones.RemoteIP', 'NUM_BUCKETS':2, # Number of buckets worth of history to keep. Must be at least 2 'BUCKET_INTERVAL':15 * 60 # Period of time to enforce limits. 'BUCKET_CAPACITY':50, # Maximum number of requests allowed within BUCKET_INTERVAL }, } # Where to store request counts. THROTTLE_BACKEND = 'throttle.backends.cache.CacheBackend' # Optional after Redis backend is chosen ('throttle.backends.redispy.RedisBackend') THROTTLE_REDIS_HOST = 'localhost' THROTTLE_REDIS_PORT = 6379 THROTTLE_REDIS_DB = 0 # Force throttling when DEBUG=True THROTTLE_ENABLED = True
使用@throttledecorator对视图强制执行限制规则:
from throttle.decorators import throttle @throttle(zone='default') def myview(request): ...
也适用于基于类的视图:
from django.views.generic import View from django.utils.decorators import method_decorator from throttle.decorators import throttle class TestView(View): @method_decorator(throttle(zone='default')) def dispatch(self, *args, **kwargs): return super(TestView, self).dispatch(*args, **kwargs) def head(self, request): ... def get(self, request): ...
Code: | https://github.com/sobotklp/django-throttle-requests |
---|---|
Documentation: | https://readthedocs.org/projects/django-throttle-requests/ |