进阶开发——文档,缓存,ip限速

一.文档自动化管理

  1.django rest framework提供了一个接口:

      可以将代码中注释转换为文档中内容(list,create等),以及help_text等等,且会生成JavaScript,Python,Shell的测试脚本,也可以直接在该接口测试。

from rest_framework.documentation import include_docs_urls
.......
urlpatterns = [
  
    # 配置drf文档
    url('^docs/', include_docs_urls(title='悦运动')),
   ......
] 

  2.效果如下:

二.django rest frmawork的缓存

  1.Django自带的缓存机制:http://djangobook.py3k.cn/2.0/chapter15/

  2.drf-extensions:https://github.com/chibisov/drf-extensions

    2.1安装:

    2.2缓存的使用(适用于retrieve和list):

1 #缓存
2 from rest_framework_extensions.cache.mixins import CacheResponseMixin
3 ......
4 #配置缓存mixin
5 class JoinScheduleViewset(CacheResponseMixin,mixins.ListModelMixin, mixins.DestroyModelMixin,
6                           mixins.CreateModelMixin,
7                           mixins.RetrieveModelMixin, viewsets.GenericViewSet):
8 ......

    2.3添加缓存过期时间(setting文件):

REST_FRAMEWORK_EXTENSIONS = {
   #15分钟
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 15 }

  3.配置redis缓存(会在redis生成相应key及内容等。不同内容格式【json,html等】对应key不同):

    3.1django-redis地址:https://github.com/niwinz/django-redis

    3.2安装:pip install django-redis

    3.3简单配置(setting中):

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
      #有密码就配置,否则直接跟redis地址,1是数据库
"LOCATION": "redis://密码@127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } }

三.Throtting对用户和ip进行限速

  1.目的:

    限制爬虫,防止爬虫对服务器造成压力,保护数据等原因。

  2.drf官方文档介绍:https://www.django-rest-framework.org/api-guide/throttling/

    2.1setting配置:

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
       #未登录
        'rest_framework.throttling.AnonRateThrottle',
       #登录后
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
     #某段时间最多反问多少次
'anon': '100/day', 'user': '1000/day' } }

 

请求超过了次数,状态码为429

      2.2view引入(解析配置,获取ip等等操作):

#引入throttle
from rest_framework.throttling import UserRateThrottle,AnonRateThrottle

class ScheduleViewset(......):
    #配置ip限制访问次数
    throttle_classes = (UserRateThrottle,AnonRateThrottle)
.......
原文地址:https://www.cnblogs.com/lyq-biu/p/9626005.html