应用层速率限制的django框架

django-throttle-requests的Python项目详细描述


为django项目实现特定于应用程序的速率限制中间件的框架

Build Status

本模块的目的是:

实现应用程序级(或略低于)速率限制规则。通常,这些规则会表示为“在定义的时间段内的最大请求”。例如:

  • IP地址每天最多可发出1500个请求
  • 具有OAuth访问令牌的用户可以进行500次读取/小时和200次写入/小时

不适用于:

令牌桶或泄漏桶过滤器:主要用于流量整形,这些算法由防火墙和服务器(如nginx)实现。

安装

  1. 使用pip安装库:

    sudo pip install django-throttle-requests
    
  2. 将目录throttle添加到项目的PYTHONPATH中。

  3. 在项目设置中插入以下配置:

    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
    
  4. 使用@throttledecorator对视图强制执行限制规则:

    from throttle.decorators import throttle
    
    @throttle(zone='default')
    def myview(request):
       ...
    
  5. 也适用于基于类的视图:

    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/

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java Intellij IDEA代码覆盖率不起作用   java如何在JavaFX8中根据其特定的祖先获取节点边界?   正则表达式在java arraylist中搜索正则表达式   运行backticks/exec()的java PHP路径问题   java正则表达式(全部替换)但不是引导一个撇号   将两个十进制整数与除法运算相乘   Java覆盖文件   spring boot Elasticsearch高级Rest客户端Java排序工作不正常   java为什么我的库不能访问它的资源?   java onCreateView,用于在选择相邻选项卡时调用选项卡?   如何在java中查找数组中一个数字的重复次数   java如何在hibernate中创建表,该表不存在于数据库中   java为什么当所有其他精灵移动时,Carpaint不移动?   java如何保存tuplas值,以便以后搜索   数据库中的java字符串使用isEmpty提供nullPointerException   AmazonWeb服务java。网ConnectException:连接被拒绝(连接被拒绝)   构造函数名和类名在Java中是相同的。为什么?