dajngo rest framwork caching,throttling

缓存

背景介绍:

动态网站的问题就在于它是动态的。 也就是说每次用户访问一个页面,服务器要执行数据库查询,启动模板,执行业务逻辑以及最终生成一个你所看到的网页,这一切都是动态即时生成的。 从处理器资源的角度来看,这是比较昂贵的。

缓存的目的是为了避免重复计算,特别是对一些比较耗时间、资源的计算。

django 自带的缓存:

内存缓存、数据库缓存、文件系统缓存、本地内存缓存、仿缓存,自定义后端缓存,本篇介绍redis+drf-extensions实现缓存。也可以自己通过装饰器和redis-py模块手动实现,较为简单。

settings.py

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

 

# 在view中使用
from django.shortcuts import render
from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def my_view(request):
    ...

# 在urlConf中使用cache
from django.views.decorators.cache import cache_page

urlpatterns = [
    path('/', cache_page(60 * 15)(IndexView.as_view())),
]

 

如下为restframework缓存配置

环境配置:

$ pip install django-redis
$ pip install drf-extensions

settings.py

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD": "mysecret"
        }
    }
}

views.py(装饰器更灵活)

from rest_framework_extensions.cache.decorators import (
    cache_response
)

class GoodsView(APIView):
    @cache_response(timeout=60*60, cache='default')
    def get(self,request,*args,**kwargs):
        ...
    # or 
    @cache_response(timeout=60*60, cache='default')
    def list(self,request,*args,**kwargs):
        ......
  • timeout 缓存时间
  • cache 缓存使用的Django缓存后端(即CACHES配置中的键名称)

 

限流

限流与权限类似,因为它确定是否应该授权请求。 限流阀指示临时状态,并用于控制客户端可以对API进行的请求速率。
与权限一样,可能会使用多种限流方式。你的 API 可能对未经身份验证的请求进行限流,对经过身份验证的请求限流较少。
如果你需要对 API 的不同部分使用不同的限流策略,由于某些服务特别占用资源,你可能想要使用同时有多种限流策略的另一种方案。
如果你想要同时实现爆发限流率和持续限流率,也可以使用多个限流阀。例如,你可能希望将用户限制为每分钟最多 60 个请求,并且每天最多 1000 个请求。
限流阀不一定只限制请求频率。例如,存储服务可能还需要对带宽进行限制,而付费数据服务可能希望对正在访问的某些记录进行限制。

限流算法:

1. 计数器算法

2. 漏桶算法

3. 令牌桶算法

restframework 自带 Throttling,也是利用了cache,统计ip,user请求次数

设置限流策略

settings.py全局设置默认限流策略

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '3/min',
        'user': '5/min'
    }
}
"""
('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day')
"""

然后在视图类中加入即可

from rest_framework.throttling import AnonRateThrottle
from rest_framework.throttling import UserRateThrottle


class DemoAPIView(APIView):
    throttle_classes = (AnonRateThrottle,UserRateThrottle)

  

 

当然也可以自定义Throttle

class VipInstantRateThrottle(UserRateThrottle):
    rate = '30/min'


class VipContinuedRateThrottle(UserRateThrottle):
    rate = '1000/day'

 

API参考

AnonRateThrottle

AnonRateThrottle 将永远限制未认证的用户。通过传入请求的 IP 地址生成一个唯一的密钥来进行限制。

允许的请求频率由以下之一决定(按优先顺序)。

1. 类的 rate 属性,可以通过继承 AnonRateThrottle 并设置属性来提供。

2. DEFAULT_THROTTLE_RATES['anon'] 设置.

如果你想限制未知来源的请求频率,AnonRateThrottle 是合适的。

 

UserRateThrottle

UserRateThrottle 通过 API 将用户请求限制为给定的请求频率。用户标识用于生成一个唯一的密钥来加以限制。未经身份验证的请求将回退到使用传入请求的 IP 地址生成一个唯一的密钥来进行限制。

允许的请求频率由以下之一决定(按优先顺序)。

1. 类的 rate 属性,可以通过继承 UserRateThrottle 并设置属性来提供。

2. DEFAULT_THROTTLE_RATES['user'] 设置.

一个 API 可能同时具有多个 UserRateThrottles。为此,请继承 UserRateThrottle 并为每个类设置一个唯一的“范围”。

posted @ 2019-03-28 20:41  家迪的家  阅读(333)  评论(0编辑  收藏  举报