应用层速率限制的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第三方库


热门话题
JavaSpringMVC控制器测试打印结果JSON字符串   若catch语句返回,那个么为什么它最终会阻塞呢?   java Grails中servletContext在哪里可用?   java Jhipster:如何为现有项目启用多种语言   java异常评估SpringEL表达式:“#fields.hasErrors('something')”   java如何验证SeleniumWebDriver中的文本颜色?   java在绘图时使用JPanel坐标   java如何初始化spring启动到project?   java如何通过JDBC的PreparedStatement将UUID数组插入HyperSQL数据库   java修改JVM以跨线程序列化文件访问   Javascript到Java正则表达式   使用Java运行时调用aspell程序时出现字符集问题。getRuntime()。执行官   执行RDP时的java Sukuli按钮识别   java如何使用okhttp更改connect请求的标头   java无法创建Maven Eclipse项目