• 接口整理


    一.课程接口

    1 class CourseModelSerializer(serializers.ModelSerializer):
    2     class Meta:
    3         model=Course
    4         fields="__all__"
    5     level=serializers.CharField(source="get_level_display")
    6     coursedetail_id=serializers.IntegerField(source="coursedetail.id")
    1 class CoursesView(mixins.ListModelMixin,mixins.CreateModelMixin,generics.GenericAPIView):
    2     queryset = Course.objects.all()
    3     serializer_class = CourseModelSerializer
    4     def get(self, request, *args, **kwargs):
    5         response=self.list(self, request, *args, **kwargs)
    6         response["Access-Control-Allow-Origin"] = "*"
    7         response["Access-Control-Allow-Headers"] = "Content-Type"
    8         return response

    课程接口数据结构

     1 [
     2     {
     3         "id": 1,
     4         "level": "初级",
     5         "coursedetail_id": 1,
     6         "name": "Python开发21天入门",
     7         "course_img": "https://hcdn1.luffycity.com/static/frontend/course/5/21%E5%A4%A9_1544059695.5584881.jpeg",
     8         "course_type": 0,
     9         "brief": "Python开发21天入门的课程概述",
    10         "pub_date": "2018-12-01",
    11         "period": 7,
    12         "order": 1,
    13         "attachment_path": null,
    14         "status": 0
    15     },
    16     {
    17         "id": 2,
    18         "level": "中级",
    19         "coursedetail_id": 2,
    20         "name": "Linux系统基础五周精讲",
    21         "course_img": "https://hcdn1.luffycity.com/static/frontend/course/12/Linux_1544069008.0915537.jpeg",
    22         "course_type": 1,
    23         "brief": "Linux系统基础五周精讲的课程概述",
    24         "pub_date": "2018-12-02",
    25         "period": 5,
    26         "order": 2,
    27         "attachment_path": null,
    28         "status": 0
    29     },
    30     {
    31         "id": 3,
    32         "level": "高级",
    33         "coursedetail_id": 3,
    34         "name": "Django入门与实践",
    35         "course_img": "https://hcdn1.luffycity.com/static/frontend/course/42/git-pc%E5%88%97%E8%A1%A8_1544420927.8406003.jpeg",
    36         "course_type": 2,
    37         "brief": "Django入门与实践的课程概述",
    38         "pub_date": "2018-12-03",
    39         "period": 23,
    40         "order": 3,
    41         "attachment_path": null,
    42         "status": 0
    43     }
    44 ]

    二.课程详情接口

     1 class CourseDetailModelSerializer(serializers.ModelSerializer):
     2     class Meta:
     3         model=CourseDetail
     4         fields="__all__"
     5     name=serializers.CharField(source="course.name")
     6     prices=serializers.SerializerMethodField()
     7     teachers=serializers.SerializerMethodField()
     8     brief=serializers.CharField(source="course.brief")
     9     stay_all_time=serializers.CharField(source="hours")
    10     level=serializers.CharField(source="course.get_level_display")
    11     teachers_info=serializers.SerializerMethodField()
    12     is_online=serializers.CharField(source="course.get_status_display")
    13     recommend_coursesinfo=serializers.SerializerMethodField()
    14     def get_teachers(self,coursedetail_obj):
    15         s=""
    16         for obj in coursedetail_obj.teachers.all():
    17             s=s+obj.name
    18         return s
    19     def get_prices(self,coursedetail_obj):
    20         price_policy_queryset=coursedetail_obj.course.price_policy.all()
    21         print(price_policy_queryset)
    22         return [{"price":price_policy.price,"valid_period":price_policy.get_valid_period_display()} for price_policy in price_policy_queryset]
    23     def get_teachers_info(self,coursedetail_obj):
    24         teachers_queryset=coursedetail_obj.teachers.all()
    25         return [{"name":teacher.name,"brief":teacher.brief,"image":teacher.image} for teacher in  teachers_queryset]
    26     def get_recommend_coursesinfo(self,coursedetail_obj):
    27         recommend_courses_queryset=coursedetail_obj.recommend_courses.all()
    28         return [{"name": recommend_courses.name, "pk": recommend_courses.pk} for recommend_courses in recommend_courses_queryset]
    1 class CourseDetailView(mixins.RetrieveModelMixin,generics.GenericAPIView):
    2     queryset = CourseDetail.objects.all()
    3     serializer_class = CourseDetailModelSerializer
    4     def get(self, request, *args, **kwargs):
    5         response=self.retrieve(self, request, *args, **kwargs)
    6         response["Access-Control-Allow-Origin"] = "*"
    7         response["Access-Control-Allow-Headers"] = "Content-Type"
    8         return response

    课程详情接口数据结构

     1 {
     2     "id": 1,
     3     "name": "Python开发21天入门",
     4     "prices": [
     5         {
     6             "price": 100,
     7             "valid_period": "1个月"
     8         },
     9         {
    10             "price": 200,
    11             "valid_period": "2个月"
    12         },
    13         {
    14             "price": 300,
    15             "valid_period": "3个月"
    16         }
    17     ],
    18     "teachers": "alex",
    19     "brief": "Python开发21天入门的课程概述",
    20     "stay_all_time": "7",
    21     "level": "初级",
    22     "teachers_info": [
    23         {
    24             "name": "alex",
    25             "brief": "alex的Brief",
    26             "image": "https://hcdn1.luffycity.com/static/frontend/course/46/Zabbiix-pc%E5%88%97%E8%A1%A8_1544431586.4417293.jpeg"
    27         }
    28     ],
    29     "is_online": "上线",
    30     "recommend_coursesinfo": [
    31         {
    32             "name": "Linux系统基础五周精讲",
    33             "pk": 2
    34         }
    35     ],
    36     "hours": 7,
    37     "course_slogan": "Python开发21天入门的Course slogan",
    38     "video_brief_link": "Python开发21天入门的Video brief link:",
    39     "why_study": "Python开发21天入门的学习原因",
    40     "what_to_study_brief": "Python开发21天入门的学习内容",
    41     "career_improvement": "Python开发21天入门的此项目如何有助于我的职业生涯:",
    42     "prerequisite": "Python开发21天入门的先修要求",
    43     "course": 1,
    44     "recommend_courses": [
    45         2
    46     ]
    47 }

    三.登录接口

     1 class LoginView(APIView):
     2     def post(self,request):
     3         user=request.data.get("user")
     4         pwd=request.data.get("pwd")
     5         user_obj=authenticate(username=user,password=pwd)
     6         res={"user": None, "msg": None}
     7         if user_obj:
     8             random_str=uuid.uuid4()
     9             Token.objects.update_or_create(user=user_obj,defaults={"key":random_str,"created":datetime.datetime.now()})
    10             res["user"]=user_obj.username
    11             res["token"]=random_str
    12         else:
    13             res["msg"]="用户名或密码错误"
    14         return Response(res)

    四.认证接口

    1 class AuthUser(BaseAuthentication):
    2     def authenticate(self, request):
    3         token=request.META.get("HTTP_AUTHORIZATION")
    4         token_obj=Token.objects.filter(key=token).first()
    5         if not token_obj:
    6             raise AuthenticationFailed("验证失败!")
    7         return (token_obj.user,token_obj)

    在需要热认证的接口中加上

    1 authentication_classes = [AuthUser]

    五.token的缓存与时效

    Django自带的cache,用来缓存,默认缓存到内存中

    1 from django.core.catch import cache
    2 cache.set("name","shy",5)#存储时间为5秒钟
    3 catch.get("name")  #shy
     1 from rest_framework.authentication import BaseAuthentication
     2 from rest_framework.exceptions import AuthenticationFailed
     3 from django.core.cache import cache
     4 from app01.models import Token
     5 import datetime
     6 import pytz
     7 #认证
     8 class AuthUser(BaseAuthentication):
     9     def authenticate(self, request):
    10         token=request.META.get("HTTP_AUTHORIZATION")
    11         token_obj=Token.objects.filter(key=token).first()
    12         print('token_obj',token_obj)
    13         print('token_obj',type(token_obj))
    14         if not token_obj:
    15             raise AuthenticationFailed("验证失败!")
    16         #检验token是否正确
    17         token_obj=Token.objects.filter(key=token).first()
    18         if token_obj:
    19         # 校验是否在有效期内
    20             now=datetime.datetime.now()
    21             now=now.replace(tzinfo=pytz.timezone("UTC"))
    22             state=now-token_obj.created<datetime.timedelta(weeks=2)
    23             if state:
    24                 delta = now - token_obj.created
    25                 delta = datetime.timedelta(weeks=2) - delta
    26                 #缓存时间不能太长,七天
    27                 cache.set(token_obj.key,token_obj.user,min(60*60*24*7,delta.total_seconds()))
    28                 return (token_obj.user,token_obj)
    29             else:
    30                 raise AuthenticationFailed("认证超时")

    六.登录接口

     1 from rest_framework.views import APIView
     2 
     3 from rest_framework.response import Response
     4 from app01.models import UserInfo,Token
     5 from django.contrib.auth import authenticate
     6 from django.http import HttpResponse
     7 from app01.utils.response import BaseResponse
     8 import uuid
     9 import datetime
    10 #登录接口
    11 class LoginView(APIView):
    12     def post(self,request):
    13         resture=BaseResponse()
    14         user=request.data.get("username")
    15         pwd=request.data.get("password")
    16         print(user,pwd)
    17         user_obj=authenticate(username=user,password=pwd)
    18         res={"user": None, "msg": None}
    19         if user_obj:
    20             random_str=uuid.uuid4()
    21             Token.objects.update_or_create(user=user_obj,defaults={"key":random_str,"created":datetime.datetime.now()})
    22             res["user"]=user_obj.username
    23             res["token"]=random_str
    24             resture.data=res
    25             resture.code=1000
    26         else:
    27             res["msg"]="用户名或密码错误"
    28             resture.msg="用户名或密码错误"
    29             resture.code = 1003
    30         print(res)
    31         return Response(resture.dict())
    32 
    33     def get(self,request):
    34         return HttpResponse("ok")

    七.级验接口

     1 from rest_framework.views import APIView
     2 from app01.utils.geetest import GeeTestLib
     3 from django.conf import settings
     4 import json
     5 from rest_framework.response import Response
     6 
     7 
     8 class CaptchaView(APIView):
     9     def get(self, request):
    10         gt = GeeTestLib(settings.GEE_TEST["gee_test_access_id"], settings.GEE_TEST["gee_test_access_key"])
    11         gt.pre_process()
    12         # 设置 geetest session, 用于是否启用滑动验证码向 geetest 发起远程验证, 如果取不到的话只是对本地轨迹进行校验
    13         # self.request.session[gt.GT_STATUS_SESSION_KEY] = status
    14         # request.session["user_id"] = user_id
    15         response_str = gt.get_response_str()
    16         response_str = json.loads(response_str)
    17 
    18         return Response({"error_no": 0, "data": response_str})

    八.购物车接口

      1 from app01.models import *
      2 from app01.utils.response import BaseResponse
      3 from app01.utils.exception import PricePoliceError
      4 
      5 from django.core.exceptions import ObjectDoesNotExist
      6 from django.conf import settings
      7 
      8 from rest_framework.views import APIView
      9 from rest_framework.response import Response
     10 import json
     11 import redis
     12 pool = redis.ConnectionPool(port=6379,decode_responses=True)
     13 cache=redis.Redis(connection_pool=pool)
     14 
     15 class ShoppingcartView(APIView):
     16     #还没加认证
     17     def post(self,request):
     18         #前端数据
     19         #课程id
     20         course_id=request.POST.get("course_id")
     21         #价格策略id
     22         price_policy_id=request.POST.get("price_policy_id")
     23         # print(course_id,price_policy_id)
     24 
     25         #用户id先写死1
     26         # user_id=request.user.id
     27         user_id=request.user.id
     28         #校验数据
     29         res = BaseResponse()
     30         try:
     31             #校验课程是否存在
     32             course_obj=Course.objects.get(pk=course_id)
     33             #校验价格策略是否合法
     34 
     35             price_policy_dict = {}
     36             for price_policy in course_obj.price_policy.all():
     37                 price_policy_dict[price_policy.pk] = {
     38                     "pk": price_policy.pk,
     39                     "valid_period": price_policy.valid_period,
     40                     "valid_period_text": price_policy.get_valid_period_display(),
     41                     "price": price_policy.price,
     42                     "default": price_policy_id == price_policy.pk
     43                 }
     44 
     45             print("price_policy_dict", price_policy_dict)
     46 
     47             if int(price_policy_id) not in [obj.pk for obj in course_obj.price_policy.all()]:
     48                 raise PricePoliceError
     49         except ObjectDoesNotExist as e:
     50             res.code=1001
     51             res.msg="课程不存在"
     52         except PricePoliceError as e:
     53             res.code = 1002
     54             res.msg = "价格策略错误"
     55 
     56         #将购物车信息写入redis
     57         '''
     58         redis数据结构
     59         redis={
     60             shoppingcar_userid_course_id:{
     61                 title:'',
     62                 img:'',
     63             },
     64             shoppingcar_1_1:{
     65                 title:'',
     66                 img:'',
     67             },
     68             shoppingcar_1_2:{
     69                 title:'',
     70                 img:'',
     71             }
     72         }
     73         '''
     74         pp = PricePolicy.objects.get(pk=price_policy_id)
     75         #将这个人的购物车信息存到redis中
     76         shoppingcar_key=settings.SHOPPINGCAR_KEY%(user_id,course_id)
     77         shoppingcar_val={
     78             "id":course_obj.pk,
     79             "name":course_obj.name,
     80             "course_img":course_obj.course_img,
     81             "relate_price_policy": price_policy_dict,
     82             "choose_price_policy_id": price_policy_id,
     83             "default_price": pp.price,
     84             "valid_period": pp.valid_period,
     85             "valid_period_text": pp.get_valid_period_display(),
     86         }
     87         cache.set(shoppingcar_key, json.dumps(shoppingcar_val))
     88         # cache.set(shoppingcar_key, [0,1])
     89         res.data = "加入购物车成功!"
     90         print("执行完了")
     91         res.data=shoppingcar_val
     92         return Response(res.dict())
     93 
     94     def get(self,request):
     95         res = BaseResponse()
     96         # cache.delete("shoppingcar_1_3")
     97         # cache.delete("shoppingcar_1_1")
     98 
     99         shopping_car_keys_list=cache.keys(pattern='shoppingcar_%s_*' % (request.user.id,))
    100         print(shopping_car_keys_list)
    101         shopping_car_list=[]
    102         num=0
    103         for key in shopping_car_keys_list:
    104             dict=json.loads(cache.get(key))
    105             shopping_car_list.append(dict)
    106             num=num+1
    107         total=num
    108 
    109         res.data= {
    110             "total": total,
    111             "shopping_car_list":shopping_car_list ,
    112                   }
    113         res.code= 1000,
    114         res.msg=""
    115         return Response(res.dict())
    116 
    117 '''
    118 理想数据类型
    119 "shopping_car_list": [
    120 
    121                 {
    122                     "id": 4,
    123                     "default_price_period": 30,
    124                     "relate_price_policy": {
    125                         "4": {
    126                             "valid_period": 30,
    127                             "valid_period_text": "1个月",
    128                             "default": True,
    129                             "prcie": 1000
    130                         },
    131                         "5": {
    132                             "valid_period": 60,
    133                             "valid_period_text": "2个月",
    134                             "default": False,
    135                             "prcie": 1500
    136                         }
    137                     },
    138                     "name": "Linux系统基础5周入门精讲",
    139                     "course_img": "https://luffycity.com/static/frontend/course/12/Linux5周入门_1509589530.6144893.png",
    140                     "default_price": 1000
    141                 }
    142             ]
    143         },
    144 '''

    九.结算接口

      1 from app01.models import *
      2 from app01.utils.response import BaseResponse
      3 from app01.utils.exception import PricePoliceError
      4 from app01.utils.exception import CommonException
      5 
      6 from django.core.exceptions import ObjectDoesNotExist
      7 from django.conf import settings
      8 
      9 from rest_framework.views import APIView
     10 from rest_framework.response import Response
     11 
     12 import redis
     13 import json
     14 import datetime
     15 cache=redis.Redis(decode_responses=True)
     16 
     17 class AccountView(APIView):
     18     # authentication_classes = [LoginAuth]
     19     def get_coupon_list(self, request, course_id=None):
     20         # print('11111111111112222222',course_id)
     21         now = datetime.datetime.utcnow()
     22         # course_id=str(course_id)
     23         coupon_record_list = CouponRecord.objects.filter(
     24             #####################3改
     25             account=1,
     26             status=0,
     27             coupon__valid_begin_date__lte=now,
     28             coupon__valid_end_date__gt=now,
     29             coupon__content_type_id=9,
     30             coupon__object_id=course_id
     31 
     32         )
     33 
     34         coupon_list = []
     35 
     36         for coupon_record in coupon_record_list:
     37             coupon_list.append({
     38 
     39                 "pk": coupon_record.pk,
     40                 "name": coupon_record.coupon.name,
     41                 "coupon_type": coupon_record.coupon.get_coupon_type_display(),
     42                 "money_equivalent_value": coupon_record.coupon.money_equivalent_value,
     43                 "off_percent": coupon_record.coupon.off_percent,
     44                 "minimum_consume": coupon_record.coupon.minimum_consume,
     45             })
     46         # print('coupon_list-----',coupon_list)
     47         return coupon_list
     48 
     49     def get(self,request):
     50         res = BaseResponse()
     51         try:
     52 
     53             account_key = settings.ACCOUNT_KEY % (request.user.id, "*")
     54 
     55             all_keys = cache.scan_iter(account_key)
     56             print('all_keys',all_keys)
     57             # 3.2 循环所有的keys 得到每个可以
     58             account_course_list = []
     59             for key in all_keys:
     60                 account_course = json.loads(cache.get(key))
     61                 account_course_list.append(account_course)
     62             # print('account_course_list',account_course_list)
     63             global_coupons_detail=cache.get("global_coupons_%s" % request.user.id)
     64             # print("global_coupons_detail-----------",global_coupons_detail)
     65             global_coupons = json.loads(str(global_coupons_detail))
     66             global_coupons_list=[]
     67             # print('global_coupons',global_coupons)
     68             for val in global_coupons:
     69                 global_coupons_list.append(val)
     70             # print('global6565',global_coupons_list)
     71             # total_price = cache.get("total_price")
     72             # print(11111111)
     73             total_price =0
     74             #对account_course_list的处理
     75             new_account_course_list=[]
     76             print(account_course_list)
     77             for item in account_course_list:
     78                 new_account_course_dict=item["course_info"]
     79                 coupons=item["coupons"]
     80                 new_account_course_dict["coupon_list"]=coupons
     81                 new_account_course_list.append(new_account_course_dict)
     82 
     83                 # print('-----------',item["default_price"])
     84                 total_price +=int(item["course_info"]["default_price"])
     85                 print(total_price)
     86 
     87             res.data = {
     88                 "account_course_list": new_account_course_list,
     89                 "total": len(account_course_list),
     90                 "global_coupons": global_coupons_list,
     91                 "total_price": total_price
     92             }
     93             # print("res.data",res.data)
     94         except Exception as e:
     95             print('----------------',e)
     96             res.code = 1033
     97             res.error = "获取购物车失败"
     98 
     99         return Response(res.dict())
    100 
    101     def post(self,request):
    102         #获取数据
    103         course_id_list=request.data.get("course_id_list")
    104         print(course_id_list)
    105         #校验数据
    106             #有可能直接购买,也有可能在购物车中购买
    107         res = BaseResponse()
    108         #构建结算字典
    109         account_val = {}
    110         course_info={}
    111         res.data = {}
    112         try:
    113             for course_id in course_id_list:
    114                 account_key=settings.ACCOUNT_KEY%(request.user.id,course_id)
    115                 #校验课程是否存在
    116                 course_obj=Course.objects.get(pk=course_id)
    117                 #            用户id先写死为1
    118                 #1.课程信息
    119                 shopping_car_key = settings.SHOPPINGCAR_KEY % (request.user.id, course_id)
    120                 course_info=json.loads(cache.get(shopping_car_key))
    121                 account_val["course_info"] = course_info
    122 
    123                 #2.优惠券信息
    124                 coupons = self.get_coupon_list(request, course_id)
    125                 account_val["coupons"]=coupons
    126 
    127                 #添加到redis中
    128                 cache.set(account_key,json.dumps(account_val))
    129 
    130                 res.data[account_key] = account_val
    131              #通用优惠券
    132             global_coupons = self.get_coupon_list(request)
    133             print('111global_coupons',global_coupons)
    134             global_coupons_val=cache.set("global_coupons_%s" % request.user.id, json.dumps(global_coupons))
    135             res.data["global_coupons_%s" % request.user.id]=global_coupons_val
    136 
    137 
    138         except ObjectDoesNotExist as e:
    139             res.code=1001
    140             res.msg="课程不存在"
    141         except PricePoliceError as e:
    142             res.code = 1002
    143             res.msg = "价格策略错误"
    144         return Response(res.dict())
    145 
    146     def cal_coupon_price(self,price,coupon_info):
    147 
    148         print("coupon_info",coupon_info)
    149         coupon_type=coupon_info["coupon_type"]
    150         money_equivalent_value=coupon_info.get("money_equivalent_value")
    151         off_percent=coupon_info.get("off_percent")
    152         minimum_consume=coupon_info.get("minimum_consume")
    153         rebate_price=0
    154         if coupon_type == "立减券": # 立减券
    155             rebate_price=price-money_equivalent_value
    156             if rebate_price <= 0:
    157                 rebate_price=0
    158         elif coupon_type == "满减券": # 满减券
    159              if minimum_consume > price:
    160                  raise CommonException(3000,"优惠券未达到最低消费")
    161              else:
    162                  rebate_price=price-money_equivalent_value
    163         elif coupon_type == "折扣券":
    164             rebate_price=price*off_percent/100
    165 
    166         return rebate_price
    167 
    168     def put(self,request, *args, **kwargs):
    169         '''
    170         choose_coupons:
    171             {
    172             choose_coupons={"1":2,"2":3,"global_coupon_id":5}
    173             is_beli:true
    174             }
    175         '''
    176         res=BaseResponse()
    177         # try:
    178 
    179         # 1 获取数据
    180         choose_coupons=request.data.get("choose_coupons")
    181         # print("choose_coupons",choose_coupons)
    182         is_beli=request.data.get("is_beli")
    183         #############################1
    184         user_pk=request.user.id
    185 
    186         # 2 获取结算课程列表
    187         cal_price={}
    188         data=self.get(request).data.get("data")
    189         # print("data",data)
    190         account_course_list=data.get("account_course_list")
    191         # print("account_course_list",account_course_list)
    192         '''
    193            account_course_list=[{
    194                 'id': 4,
    195                 'coupon_list': [{
    196                     'off_percent': None,
    197                     'pk': 4,
    198                     'money_equivalent_value': 300.0,
    199                     'coupon_type': '立减券',
    200                     'minimum_consume': 0,
    201                     'name': '51劳动节'
    202                 }],
    203                 'course_img': 'https://luffycity.com/static/frontend/course/12/Linux5周入门_1509589530.6144893.png',
    204                 'default_price': 1500.0,
    205                 'default_price_period': 60,
    206                 'relate_price_policy': {
    207                     '5': {
    208                         'valid_period_text': '2个月',
    209                         'default': True,
    210                         'valid_period': 60,
    211                         'prcie': 1500.0
    212                     },
    213                     '4': {
    214                         'valid_period_text': '1个月',
    215                         'default': False,
    216                         'valid_period': 30,
    217                         'prcie': 1000.0
    218                     }
    219                 },
    220                 'default_price_policy_id': 5,
    221                 'name': 'Linux系统基础5周入门精讲'
    222             }, {
    223                 'id': 2,
    224                 'coupon_list': [{
    225                     'off_percent': 80,
    226                     'pk': 3,
    227                     'money_equivalent_value': 0.0,
    228                     'coupon_type': '折扣券',
    229                     'minimum_consume': 0,
    230                     'name': '清明节活动'
    231                 }],
    232                 'course_img': 'https://luffycity.com/static/frontend/course/3/Django框架学习_1509095212.759272.png',
    233                 'default_price': 300.0,
    234                 'default_price_period': 30,
    235                 'relate_price_policy': {
    236                     '3': {
    237                         'valid_period_text': '1个月',
    238                         'default': True,
    239                         'valid_period': 30,
    240                         'prcie': 300.0
    241                     },
    242                     '1': {
    243                         'valid_period_text': '1周',
    244                         'default': False,
    245                         'valid_period': 7,
    246                         'prcie': 100.0
    247                     },
    248                     '2': {
    249                         'valid_period_text': '2周',
    250                         'default': False,
    251                         'valid_period': 14,
    252                         'prcie': 200.0
    253                     }
    254                 },
    255                 'default_price_policy_id': 3,
    256                 'name': 'Django框架学习'
    257             }]
    258         '''
    259         account_courses_info={}
    260         # print("account_course_list",account_course_list)
    261         for account_course in account_course_list:
    262             temp={
    263                 "coupon":{},
    264                 "default_price":account_course["default_price"]
    265             }
    266             account_courses_info[account_course["id"]]=temp
    267 
    268             for item in account_course["coupon_list"]:
    269 
    270                 # print("choose_coupons",choose_coupons) # {'4': 4}
    271                 # print(str(account_course["id"]))
    272 
    273                 coupon_id=choose_coupons.get(str(account_course["id"]))
    274                 # print("-----------------")
    275                 # print(type(coupon_id))
    276                 # print(type(item["pk"]))
    277                 # print(item)
    278                 # print(coupon_id == item["pk"])
    279                 if coupon_id == str(item["pk"]):
    280                     temp["coupon"]=item
    281         print('temp',temp)
    282         print("account_course_info",account_courses_info)
    283         price_list=[]
    284         total_price=0
    285         '''
    286            {
    287                 2: {
    288                     'coupon': {  
    289                         'money_equivalent_value': 0.0,
    290                         'name': '清明节活动',
    291                         'pk': 3,
    292                         'off_percent': 80,
    293                         'coupon_type': '折扣券',
    294                         'minimum_consume': 0
    295                     },
    296                     'default_price': 200.0
    297                 }
    298             }
    299         '''
    300         for key,val in account_courses_info.items():
    301             if not val.get("coupon"):
    302                 price_list.append(val["default_price"])
    303                 cal_price[key]=val["default_price"]
    304             else:
    305                 coupon_info=val.get("coupon")
    306                 default_price=val["default_price"]
    307                 rebate_price=self.cal_coupon_price(default_price,coupon_info)
    308                 price_list.append(rebate_price)
    309                 cal_price[key]=rebate_price
    310 
    311         print("课程优惠券后价格列表price_list",price_list)
    312         total_price=sum(price_list)
    313         # 3 计算通用优惠券的价格
    314         global_coupon_id=choose_coupons.get("global_coupon_id")
    315         if global_coupon_id:
    316 
    317             global_coupons=data.get("global_coupons")
    318             print("global_coupons",global_coupons)
    319             global_coupon_dict={}
    320             for item in global_coupons:
    321                 global_coupon_dict[item["pk"]]=item
    322             total_price=self.cal_coupon_price(total_price,global_coupon_dict[global_coupon_id])
    323             print("通用优惠券",global_coupon_dict[global_coupon_id]["coupon_type"])
    324             print("计算后total_price=",total_price)
    325 
    326         # 计算贝里
    327         print("beili",is_beli,type(is_beli))
    328         print("北里",is_beli)
    329         # if is_beli:
    330         #     print("request.user.beli",request.user.beli)
    331         #     total_price=total_price-request.user.beli/10
    332         #     if total_price<0:
    333         #         total_price=0
    334         #     print("贝里数计算后",total_price)
    335         print('total_price',total_price)
    336         cal_price["total_price"]=total_price
    337         res.data=cal_price
    338         print("res.data",res.data)
    339         # except Exception as e:
    340         #     res.code=500
    341         #     res.msg="结算错误!"+str(e)
    342 
    343         return Response(res.dict())

    十.公钥,私钥

    特点:彼此互解

    作用:

    1.加密数据(公钥加密)

    2.数字签名(私钥加密)

  • 相关阅读:
    @babel/preset-env 解决Promise被Babel编译成regenerator 运行时错误问题
    Blob ArrayBuffer 和 BinaryString StringView
    TypeScript 的尴尬:模块不如wepback完善
    Node.js(1) http和https模块发送HTTP(S)请求
    axios
    Nest.js 再探 解析HTTP请求
    红楼梦题词
    倾斜摄影
    重新认识TypeScript
    TypeScript 家族
  • 原文地址:https://www.cnblogs.com/shanghongyun/p/10069070.html
Copyright © 2020-2023  润新知