rest_framework常用设置

1.常用配置

import django_filters

from django.db.models import Q
from rest_framework.pagination import PageNumberPagination
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from rest_framework import mixins
from rest_framework import viewsets
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework import permissions from .models import Goods class GoodsFilter(django_filters.rest_framework.FilterSet):
"""
商品的过滤类
"""
pricemin = django_filters.NumberFilter(field_name='shop_price', help_text="最低价格", lookup_expr='gte')
pricemax = django_filters.NumberFilter(field_name='shop_price', lookup_expr='lte')
# method 内置的方法不能满足时候,我们可以自己写自己的规则, 通过method指定函数名称 通过top_category自己定的的字段搜索
top_category = django_filters.NumberFilter(method='top_category_filter')
    # contacts 模糊查询 i表示忽然大小写
      name = django_filters.CharFilter(name='name', lookup_expr='icontacts')
    def top_category_filter(self, queryset, name, value):
return queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) | Q(
category__parent_category__parent_category_id=value)) class Meta:
model = Goods
fields = ['pricemin', 'pricemax', 'is_hot', 'is_new'] class GoodsPagination(PageNumberPagination):
'''
分页设置
'''
page_size = 10
page_size_query_param = 'page_size'
page_query_param = "page"
max_page_size = 100 class IsOwnerOrReadOnly(permissions.BasePermission):
"""
权限配置
""" # 先执行 has_permission 任何执行has_object_permission 函数
def has_permission(self, request, view):
pass def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True # Instance must have an attribute named `owner`.
return obj.user == request.user # 缓存 setting配置
REST_FRAMEWORK_EXTENSIONS = {
# 缓存时间
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 60,
# 缓存存储
'DEFAULT_USE_CACHE': 'default',
} # CacheResponseMixin 缓存
class GoodsListViewSet(CacheResponseMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
"""
商品列表页, 分页, 搜索, 过滤, 排序
"""
# throttle_classes = (UserRateThrottle, )
queryset = Goods.objects.all()
serializer_class = GoodsSerializer
# 分页配置
pagination_class = GoodsPagination
# 登入认证
authentication_classes = (JSONWebTokenAuthentication,)
# 过滤配置 DjangoFilterBackend 搜索配置SearchFilter 排序配置OrderingFilter
filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
# 过滤
filter_class = GoodsFilter
# 搜索
search_fields = ('name', 'goods_brief', 'goods_desc')
# 排序
ordering_fields = ('sold_num', 'shop_price')
# 权限认证 IsAuthenticated允许任何认证用户访问 IsAuthenticatedOrReadOnly为验证身份用户可以读
permission_classes = (permissions.IsAuthenticated, IsOwnerOrReadOnly)

2.获取user

# 获取user模型
user = self.context['request'].user
user = request.user
user = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
from django.contrib.auth import get_user_model
User = get_user_model()

3.返回数据

class IndexCategorySerializer(serializers.ModelSerializer):
   # 在model字段中加 related_name='brands'
brands = BrandSerializer(many=True)
# 自己定义模型里没有的字段返回
goods = serializers.SerializerMethodField()
sub_cat = CategorySerializer2(many=True)
ad_goods = serializers.SerializerMethodField() def get_ad_goods(self, obj):
goods_json = {}
ad_goods = IndexAd.objects.filter(category_id=obj.id, )
if ad_goods:
good_ins = ad_goods[0].goods
goods_json = GoodsSerializer(good_ins, many=False, context={'request': self.context['request']}).data
return goods_json
# 已get_字段名称 自己定义方法返回数据
def get_goods(self, obj):
all_goods = Goods.objects.filter(Q(category_id=obj.id) | Q(category__parent_category_id=obj.id) | Q(
category__parent_category__parent_category_id=obj.id))
goods_serializer = GoodsSerializer(all_goods, many=True, context={'request': self.context['request']})
return goods_serializer.data class Meta:
model = GoodsCategory
fields = "__all__"

4.rest framework关闭csrf_token认证

1.创建middleware.py
2.写入
from django.utils.deprecation import MiddlewareMixin class DisableCSRFCheck(MiddlewareMixin):
def process_request(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
3.在setting中注册中间件
'database.middleware.DisableCSRFCheck'

  

aa

上一篇:Mac 系统安装教程


下一篇:Unity删除或更换天空盒