知识小回顾之json序列化问题
精髓:支持python的几种数据类型(注意不是对象,不能放对象),其次是tuple变list。
ensure_ascii:默认值True,如果dict内含有non-ASCII的字符,则会类似uXXXX的显示数据,设置成False后,就能正常显示
一 显示视频
1.用到了cc视频的服务。
2.购买服务,上传视频,上传完成有个视频id。
3.审核通过可以拿到视频的js,html等代码,复制到模板上就可以用了。
最后:视频的一个播放规则,请阅读api。例如输入密码才能观看,付费(试看几分钟)等。
二 Redis存购物车数据
知识回顾:用redis:先安装redis,django项目再安装django_redis、settings配置、导入模块。
1.我们用的str类型存的 key:'shoppingcar_%s'%user.id value:序列化的字典
{ "1": { "title": "django", "img": "test/django.jpg", "default_cenue": 1, "cenue_all": { "1": { "date": "1u4e2au6708", "price": "10.00" }, "6": { "date": "6u4e2au6708", "price": "60.00" } } }, "2": { "title": "go", "img": "test/go.jpg", "default_cenue": 3, "cenue_all": { "3": { "date": "3u4e2au6708", "price": "10.00" } } } }
2.view
from rest_framework.views import APIView from rest_framework.response import Response from api import models from api.utils.commonUtils import MyResponse from rest_framework.viewsets import ViewSetMixin from django.core.exceptions import ObjectDoesNotExist from django.conf import settings from api.utils.MyAuth import LoginAuth from api.utils.commonUtils import CommonException from django_redis import get_redis_connection import json # 需要登录之后才能操作,写一个认证组件 class ShoppingCart(APIView): authentication_classes = [LoginAuth] conn = get_redis_connection() def post(self, request, *args, **kwargs): response = MyResponse() # 课程id,价格策略id # {"course_id": "1", "policy_id": "1"} # 放到redis中key值 shoppingcart_userid_courseid # 0 取出课程id,价格策略id course_id = str(request.data.get('course_id')) policy_id = str(request.data.get('policy_id')) # 1 校验课程是否合法 try: course = models.Course.objects.get(pk=course_id) # 2 获取所有价格策略(通过课程拿出所有价格策略) policy_price_all = course.price_policy.all() # 3 从redis中取出当前登录用户的购物车 shopping_byte = self.conn.get('shoppingcart_%s' % request.user.pk) if shopping_byte: shopping_cart = json.loads(shopping_byte) else: shopping_cart = {} # 循环构造出价格策略大字典 policy = {} for policy_price in policy_price_all: ''' { "period":3, "period_display":"3天", "price":200 }, ''' policy_one = { 'period': policy_price.pk, 'period_display': policy_price.get_valid_period_display(), 'price': policy_price.price } policy[str(policy_price.pk)] = policy_one # 判断价格策略是否合法,不再字典中,就不合法 if policy_id not in policy: # 不合法 raise CommonException(102, '价格策略不合法,你不是人') # 判断传入的课程id是否在购物车中 if course_id in shopping_cart: # 更新一下默认价格策略 shopping_cart[course_id]['default_policy'] = policy_id response.msg = '更新成功' else: shopping_course = { 'title': course.name, 'img': course.course_img, 'default_policy': policy_id, 'policy': policy } # 添加到购物车 shopping_cart[course_id] = shopping_course response.msg = '添加成功' # 写入redis self.conn.set('shoppingcart_%s' % request.user.pk, json.dumps(shopping_cart)) except ObjectDoesNotExist as e: response.status = 101 response.msg = '该课程不存在,你可能是爬虫' except CommonException as e: response.status = e.status response.msg = e.msg except Exception as e: response.status = 400 response.msg = '未知错误' print(str(e)) return Response(response.get_dic) def put(self,request,*args,**kwargs): response=MyResponse() # 0 取出课程id,价格策略id course_id = str(request.data.get('course_id')) policy_id = str(request.data.get('policy_id')) try: shopping_byte = self.conn.get('shoppingcart_%s' % request.user.pk) if shopping_byte: shopping_cart = json.loads(shopping_byte) else: shopping_cart = {} if course_id not in shopping_cart: raise CommonException(102,'要修改的课程不存在') course_detail=shopping_cart.get(course_id) if policy_id not in course_detail['policy']: raise CommonException(103, '价格策略不合法') course_detail['default_policy']=policy_id response.msg='修改成功' self.conn.set('shoppingcart_%s' % request.user.pk, json.dumps(shopping_cart)) except ObjectDoesNotExist as e: response.status = 101 response.msg = '该课程不存在,你可能是爬虫' except CommonException as e: response.status = e.status response.msg = e.msg except Exception as e: response.status = 400 response.msg = '未知错误' print(str(e)) return Response(response.get_dic) def get(self,request,*args,**kwargs): response=MyResponse() try: shopping_byte = self.conn.get('shoppingcart_%s' % request.user.pk) if shopping_byte: shopping_cart = json.loads(shopping_byte) else: shopping_cart = {} response.data=shopping_cart except Exception as e: response.status = 400 response.msg = '未知错误' print(str(e)) return Response(response.get_dic) def delete(self, request, *args, **kwargs): response=MyResponse() course_id=request.data.get('course_id') try: shopping_byte = self.conn.get('shoppingcart_%s' % request.user.pk) if shopping_byte: shopping_cart = json.loads(shopping_byte) else: shopping_cart = {} shopping_cart.pop(course_id,None) self.conn.set('shoppingcart_%s' % request.user.pk, json.dumps(shopping_cart)) except Exception as e: response.status = 400 response.msg = '未知错误' print(str(e)) return Response(response.get_dic)
总结:序列化问题:
1.django的序列化组件只能序列化对应的model。
2.像我们这种每个表都拿一点组成的字典只能用json来序列化。
3.其次序列化的是数据类型不是对象(filefelid格式的文件路径 要加str)等。
三 优惠券相关
1.优惠券种类表,用户持券表
#用户持券表(用户领取卷) class GETCoupon(models.Model): coupon=models.ForeignKey(to='SETCoupon',on_delete=models.CASCADE) num=models.CharField(max_length=64,verbose_name='用来计数') user=models.ForeignKey(to='User',verbose_name='拥有者',on_delete=models.CASCADE) status_choices=((0,'未使用'),(1,'已使用'),(2,'已过期')) status=models.IntegerField(choices=status_choices,verbose_name='优惠券状态',default=0) get_time=models.DateTimeField(verbose_name='领券时间',auto_now_add=True) use_time=models.DateTimeField(verbose_name='使用时间',blank=True,null=True) class Meta: verbose_name_plural='用户持券表' def __str__(self): return '%s-%s-%s'%(self.user,self.coupon,self.get_status_display()) #优惠券类型表(管理元创建) class SETCoupon(models.Model): # 生成优惠券 name=models.CharField(max_length=32,verbose_name='名称') brief=models.TextField(verbose_name='优惠券介绍') coupon_type_choices=((0,'立减券'),(1,'打折券'),(2,'满减券')) coupon=models.IntegerField(choices=coupon_type_choices,verbose_name='卷类型') #各种卷的价值 money_jian=models.IntegerField(verbose_name='直接减',blank=True,null=True) money_zhe=models.PositiveIntegerField(verbose_name='折扣百分比',help_text='例 7.9折,写79',blank=True,null=True) money_man=models.IntegerField(verbose_name='满减券',default=0,help_text='仅在满减券填写该字段') #各种券又分种类:网站所有商品通用的,某个商品的,减了又减 content_type=models.ForeignKey(ContentType,blank=True,null=True,on_delete=models.CASCADE) object_id=models.IntegerField(verbose_name='商品id',blank=True,null=True,help_text='某个商品表下的某个商品id') content_obj=GenericForeignKey() #生成优惠卷:数量,有效期等 coupon_num=models.IntegerField(verbose_name='张数',default=0) start_get_time=models.DateTimeField('开始领卷的时间') end_get_time=models.DateTimeField('领卷的结束时间') start_valid_time=models.DateTimeField('开始有效时间') end_valid_time=models.DateTimeField('有效结束时间') data=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural='优惠券表' def __str__(self): return "%s(%s)"%(self.get_coupon_display(),self.name)