【Vue+Django REST framework实战】第10章—— 首页、商品数量、缓存、限速功能开发

网友投稿 739 2022-09-27

【Vue+Django REST framework实战】第10章—— 首页、商品数量、缓存、限速功能开发

【Vue+Django REST framework实战】第10章—— 首页、商品数量、缓存、限速功能开发

轮播图接口实现和vue调试

#轮播图urlrouter.register(r'banners', BannerViewset, base_name="banners")

class BannerViewset(mixins.ListModelMixin, viewsets.GenericViewSet): """ 获取轮播图列表 """ queryset = Banner.objects.all().order_by("index") serializer_class = BannerSerializer

class BannerSerializer(serializers.ModelSerializer): class Meta: model = Banner fields = "__all__"

首页商品分类显示功能-

#首页商品系列数据router.register(r'indexgoods', IndexCategoryViewset, base_name="indexgoods")

class IndexCategoryViewset(mixins.ListModelMixin, viewsets.GenericViewSet): """ 首页商品分类数据 """ queryset = GoodsCategory.objects.filter(is_tab=True, name__in=["生鲜食品", "酒水饮料"]) serializer_class = IndexCategorySerializer

class IndexCategorySerializer(serializers.ModelSerializer): 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 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__"class BrandSerializer(serializers.ModelSerializer): class Meta: model = GoodsCategoryBrand fields = "__all__"class CategorySerializer2(serializers.ModelSerializer): sub_cat = CategorySerializer3(many=True) class Meta: model = GoodsCategory fields = "__all__"

使用信号实现代码分离性,完成收藏数修改

# -*- coding: utf-8 -*-__author__ = 'bobby'from django.db.models.signals import post_save, post_deletefrom django.dispatch import receiverfrom rest_framework.authtoken.models import Tokenfrom django.contrib.auth import get_user_modelfrom user_operation.models import UserFav@receiver(post_save, sender=UserFav)def create_userfav(sender, instance=None, created=False, **kwargs): if created: goods = instance.goods goods.fav_num += 1 goods.save()@receiver(post_delete, sender=UserFav)def delete_userfav(sender, instance=None, created=False, **kwargs): goods = instance.goods goods.fav_num -= 1 goods.save()

商品库存和销量修改

#购物车urlrouter.register(r'shopcarts', ShoppingCartViewset, base_name="shopcarts")

class ShoppingCartViewset(viewsets.ModelViewSet): """ 购物车功能 list: 获取购物车详情 create: 加入购物车 delete: 删除购物记录 """ permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) serializer_class = ShopCartSerializer lookup_field = "goods_id" def perform_create(self, serializer): shop_cart = serializer.save() goods = shop_cart.goods goods.goods_num -= shop_cart.nums goods.save() def perform_destroy(self, instance): goods = instance.goods goods.goods_num += instance.nums goods.save() instance.delete() def perform_update(self, serializer): existed_record = ShoppingCart.objects.get(id=serializer.instance.id) existed_nums = existed_record.nums saved_record = serializer.save() nums = saved_record.nums-existed_nums goods = saved_record.goods goods.goods_num -= nums goods.save() def get_serializer_class(self): if self.action == 'list': return ShopCartDetailSerializer else: return ShopCartSerializer def get_queryset(self): return ShoppingCart.objects.filter(user=self.request.user)

drf配置redis缓存

settings配置文件:

pip install django-redisCACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }}

drf的throttle设置api的访问速率

REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), # 用户api访问限速 # 'DEFAULT_THROTTLE_CLASSES': ( # 'rest_framework.throttling.AnonRateThrottle', # 'rest_framework.throttling.UserRateThrottle' # ), # 'DEFAULT_THROTTLE_RATES': { # 'anon': '2/minute', # 匿名用户访问 1分钟2次 # 'user': '3/minute' # 登陆用户访问 1分钟3次 # }}

class GoodsListViewSet(CacheResponseMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ 商品列表页, 分页, 搜索, 过滤, 排序 """ # throttle_classes = (UserRateThrottle, )

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:操作系统中进程和线程的关系
下一篇:【python爬虫】第12章——scrapy框架之递归解析和post请求
相关文章

 发表评论

暂时没有评论,来抢沙发吧~