zoukankan      html  css  js  c++  java
  • DRF常用功能

    ModelViewSet过滤,排序,分页,限流设置

    路由设置
    # 进行导包
    from django.urls import path,include
    from .views import *
    from rest_framework.routers import SimpleRouter,DefaultRouter
    # 设置路由
    router = DefaultRouter()
    router.register('users',UserModelApi)  # users是路由地址,UserModelApi是视图里的类方法
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('',include('router.urls'))
    ]
    
    过滤
    # 过滤功能需要导包
    from rest_framework.filters import OrderingFilter
    from django_filters.rest_framework import DjangoFilterBackend
    
    # 添加过滤功能,指定字段进行过滤查询
    filter_backends = (DjangoFilterBackend,OrderingFilter)
    filter_fields = ['username']  # 类模型里的字段名,路由里的参数
    
    排序
    # 排序功能需要导包
    from rest_framework.filters import OrderingFilter
    # 排序功能
    ordering_fields = ('需要排序的字段名',‘age’)   # 需要从路由上传参ordering,默认为id
    
    分页
    # 分页功能需要导包
    from rest_framework.pagination import PageNumberPagination
    
    # 分页(局部):自定义分页器 局部
    class PageNum(PageNumberPagination):
    	# 查询字符串中代表每页返回数据数量的参数名, 默认值: None
    	page_size_query_param = 'page_size'
    	# 查询字符串中代表页码的参数名, 有默认值: page
    	# page_query_param = 'page'
    	# 一页中最多的结果条数
    	max_page_size = 2
        
    class UserModelApi(ModelViewSet):
        # 使用自带方法 pagination_class 实例化上面定义的类
        pagination_class = StanPagginaton
    
    限流设置
    REST_FRAMEWORK = {   # 防爬虫
        'DEFAULT_THROTTLE_CLASSES':(
            'rest_framework.throttling.AnonRateThrottle',
            'rest_framework.throttling.AnonRateThrottle',
        ),
        'DEFAULT_THROTTLE_RATES':{
            'anon':'100/day',   # 未认证用户每天100次
            'user':'1000/day'   # 认证用户每天能访问1000次
        }
    }
    

  • 相关阅读:
    win10家庭版添加远程桌面服务功能
    GNS3测试NAT元件功能
    prometheus监控系统之snmp-exporter部署来监控交换机端口流量
    GNS3内网配置虚拟机测试
    GNS3内网通过cloud与实际网络实现互连互通的实验(使用环回网口)
    添加对docker的监控
    docker环境下的Grafana安装
    prometheus配置pushgateway功能测试
    京东html面单
    顺丰html面单
  • 原文地址:https://www.cnblogs.com/sleepimg/p/13891881.html
Copyright © 2011-2022 走看看