def patch(self, request, *args, **kwargs): """修改结算中心数据""" user_id = request.user.id ret = BaseResponse() course_id = request.data.get('course_id') coupon_id = request.data.get('coupon_id') payment_key = settings.PAYMENT_KEY % (user_id, course_id) payment_global_key = settings.PAYGLOBAL_KEY%(user_id) # 修改全品类优惠券 if not course_id: payment_global_dict = json.loads(self.conn.hget(payment_global_key, 'coupon').decode('utf8')) if str(coupon_id) == '0': self.conn.hset(payment_global_key, 'default_coupon', 0) if coupon_id not in payment_global_dict: ret.error = '没有该优惠券' ret.code = 4002 return Response(ret.__dict__) self.conn.hset(payment_global_key, 'default_coupon', coupon_id) ret.data = '全品类修改成功' return Response(ret.__dict__) coupon_dict = json.loads(self.conn.hget(payment_key, 'coupon').decode('utf8')) if str(coupon_id) == '0': self.conn.hset(payment_key, 'default_coupon', 0) if coupon_id not in coupon_dict: ret.error = '没有该优惠券' ret.code = 4002 return Response(ret.__dict__) self.conn.hset(payment_global_key, 'default_coupon', coupon_id) ret.data = '全品类修改成功' return Response(ret.__dict__)
def post(self, request, *args, **kwargs): """创建一条购物车信息""" ret = BaseResponse() try: courseId = int(request.data.get('courseId')) course_obj = Course.objects.get(pk=courseId) policy_id = int(request.data.get('policy_id')) redis_key = settings.SHOPPING_CAR_KEY%(request.user.id, courseId) policy = {} for item in course_obj.price_policy.all(): policy[item.id] = {'name':item.get_valid_period_display(),'price':item.price} if policy_id not in policy: raise PricePolicyInvalid('价格策略不合法') redis_value = {'title':course_obj.name, 'image':course_obj.course_img, 'policy':json.dumps(policy), 'default_policy': policy_id} if self.conn.exists(redis_key): ret.data = '购物车中该套餐已更新成功' else: ret.data = '添加到购物车成功' self.conn.hmset(redis_key, redis_value) except PricePolicyInvalid as e: ret.code = 2001 ret.error = e.msg except ObjectDoesNotExist as e: ret.code = 2002 ret.error = '课程不存在' except Exception as e: ret.code = 2003 ret.error = '获取购物车失败' return Response(ret.__dict__)
def get(self, request, version): ret = BaseResponse() try: queryset = DegreeCourse.objects.all() serializer = DegreeCourseSerializer(queryset, many=True) ret.data = serializer.data except Exception as e: print(e) ret.data = 0 ret.error = '获取数据失败' return Response(ret.dict)
def destroy(self, request, *args, **kwargs): ret = BaseResponse() course_id = request.data.get('course_id') price_id = request.data.get('price_id') key = settings.LUFFY_SHOPPING_CAR % ( 1, course_id, ) if not CONN.exists(key): ret.code = 10007 ret.error = '课程不存在' return Response(ret.dict) price_policy_dict = json.loads( CONN.hget(key, 'price_policy_dict').decode('utf-8')) if price_id not in price_policy_dict: ret.code = 10008 ret.error = '价格策略不存在' return Response(ret.dict) CONN.hset(key, 'default_price_id', price_id) CONN.expire(key, 20 * 60) ret.data = '修改成功' return Response(ret.dict)
def list(self, request, *args, **kwargs): ret = BaseResponse() # 购物车详细信息 try: shopping_car_course_list = [] # pattern = 'shopping_car_%s_*'%(USER_ID) pattern = settings.LUFFY_SHOPPING_CAR % (USER_ID, '*') user_key_list = CONN.keys(pattern) print(user_key_list) for key in user_key_list: temp = { 'id': CONN.hget(key, 'id').decode('utf-8'), 'name': CONN.hget(key, 'name').decode('utf-8'), 'img': CONN.hget(key, 'img').decode('utf-8'), 'default_price_id': CONN.hget(key, 'default_price_id').decode('utf-8'), 'price_policy_dict': json.loads( CONN.hget(key, 'price_policy_dict').decode('utf-8')), } shopping_car_course_list.append(temp) ret.data = shopping_car_course_list except Exception as e: ret.code = 500 ret.error = '获取购物车失败' return Response(ret.dict)
def get_data(self): ret = BaseResponse() try: # 从数据库获取数据 queryset = self.queryset.order_by('id') # 分页 page = PageNumberPagination() course_list = page.paginate_queryset(queryset, self.request, self) # 分页之后的结果执行序列化 ser = self.serializer_class(instance=course_list, many=True) # print(ser.data) if not ser.data: ret.code = 500 ret.error = '数据为空' else: ret.data = ser.data except Exception as e: print(e) ret.code = 500 ret.error = '获取数据失败' return ret.dict
def get(self, request, version): response = BaseResponse() try: if request.query_params.get('a'): queryset = Course.objects.filter(degree_course__isnull=True) else: queryset = Course.objects.all() p = CoursePagination() course_list = p.paginate_queryset(queryset=queryset, request=request, view=self) print(course_list) serializer = CourseSerializer(course_list, many=True) # serializer.data OrderedDict有序字典列表 print(serializer.data) response.data = serializer.data print() except Exception as e: response.code = 0 response.error = '获取数据失败' return Response(response.dict) # vars(object)
def destroy(self,request,*args,**kwargs): ''' 需求:用户选中购物车中的某个商品,点击删除,即删除购物车中此商品信息。 方案:前端将携带着 删除的商品ID 发送到后端; 后端获取到商品ID 和 用户ID 后,通过删除Redis中的键来删除购物车中该商品信息。 code : 1006 --> 用户所选的商品不在购物车中 ; 1007 --> 购物车中的该商品删除失败 ''' # 1. 获取响应数据的实例化对象 response = BaseResponse() try: # 2. 获取当前访问用户ID user_id = request.user.pk # 3. 获取前端发送过来的商品ID course_id = kwargs.get('pk') # 4. 通过获取到的用户ID 和 商品ID 来获取Redis中的键 shopping_car_key = settings.SHOPPING_CAR_KEY.format(user_id,course_id) # 5. 校验购物车中是否有此键,若没有此键则抛出异常 if not self.conn.exists(shopping_car_key): raise CourseDoesNotExist # 6. 校验成功后,通过键删除购物车中的此商品信息 self.conn.delete(shopping_car_key) # 7. 删除成功后,返回给前端消息 response.data = '购物车中的该商品已删除!' except CourseDoesNotExist as e: response.code = 1006 response.error = e.error except Exception as e: response.code = 1007 response.error = '购物车中的该商品删除失败!' return Response(response.dict)
def destroy(self, request, *args, **kwargs): """ 删除购物车中的某个课程 :param request: :param args: :param kwargs: :return: """ response = BaseResponse() try: #首先得到一个课程id course_id = request.GET.get('course_id') # key = "shopping_car_%s_%s" % (USER_ID,courseid) key = settings.LUFFY_SHOPPING_CAR % ( USER_ID, course_id, ) CONN.delete(key) # 在Redis中将带有这个课程id的hash删除 response.data = '删除成功' except Exception as e: response.code = 10006 response.error = '删除失败' return Response(response.dict)
def login(self, request, *args, **kwargs): """ 用户登录认证 :param request: :param args: :param kwargs: :return: """ response = BaseResponse() try: user = request.data.get("username") pwd = request.data.get('password') obj = models.Account.objects.filter(username=user, password=pwd).first() if not obj: response.code = 10002 response.error = '用户名或密码错误' else: uid = str(uuid.uuid4()) models.UserToken.objects.update_or_create( user=obj, defaults={'token': uid}) response.code = 99999 response.data = uid except Exception as e: response.code = 10005 response.error = '操作异常' return Response(request.dict)
def get(self): nid = request.args.get("nid", "", type=int) # status = request.args.get("status", "1", type=int) page = request.args.get("page", 1, type=int) num = request.args.get("num", per_page, type=int) # extra = {"status": status} extra = {} ftp_user = request.args.get("ftp_user") res = BaseResponse() if nid: extra["nid"] = nid if ftp_user: extra["ftp_user"] = ftp_user ftps = Ftp.search(extra, page, num) if not ftps.items: page = ftps.pages ftps = Ftp.search(extra, page, num) res.pages = ftps.pages if ftps.has_prev: res.prev = page - 1 if ftps.has_next: res.next = page + 1 res.data = [ftp.to_json() for ftp in ftps.items] res.page = page res.total = ftps.pages * num return res.dict
def put(self): self.parser.parse_args() orgin_data = request.json nid = orgin_data.pop("nid") if nid == "": return api_abort(errcode=4012) # 站点名、路径不支持修改 orgin_data.pop("ftp_user", "") orgin_data.pop("ftp_path", "") ftp_obj = Ftp.get(nid) if ftp_obj: if orgin_data: self.ftpop.update_ftp(status=orgin_data.get("status"), ftp_user=ftp_obj.ftp_user, ftp_passwd=orgin_data.get("ftp_passwd")) Ftp.update(nid, orgin_data) ftp_dict = ftp_obj.to_json() res = BaseResponse() res.data = ftp_dict return res.dict else: # 未传入修改的值 return api_abort(errcode=4019) else: # 记录不存在 return api_abort(errcode=4018)
def get(self, request, *args, **kwargs): """获取结算中心数据""" ret = BaseResponse() user_id = request.user.id key_list = self.conn.keys(settings.PAYMENT_KEY % (user_id, '*')) course_list = [] for key in key_list: info = {} data = self.conn.hgetall(key) for k, v in data.items(): kk = k.decode('utf8') if kk == 'coupon': v = json.loads(v.decode('utf8')) else: v = v.decode('utf8') info[kk] = v course_list.append(info) pay_global_key = settings.PAYGLOBAL_KEY % user_id # global_coupon的值直接使用hgetall(key) 会报错,因为json序列化的时候key必须是str,不能使bytes ret.data = { 'course_list': course_list, 'global_coupon': { 'coupon': json.loads(self.conn.hget(pay_global_key, 'coupon').decode('utf-8')), 'default_coupon': self.conn.hget(pay_global_key, 'default_coupon').decode('utf-8') } } return Response(ret.__dict__)
def get(self,request, *args, **kwargs): """ 查看购物车中所有的商品 :param request: :param args: :param kwargs: :return: """ ret = BaseResponse() try: key_match = settings.SHOPPING_CAR_KEY %(request.auth.user_id,"*") course_list = [] for key in self.conn.scan_iter(key_match,count=10): print(key) info = { "title":self.conn.hget(key,'title').decode('utf-8'), "img":self.conn.hget(key,'img').decode('utf-8'), "policy":json.loads(self.conn.hget(key,'policy').decode('utf-8')), "default_policy":self.conn.hget(key,'default_policy').decode('utf-8') } course_list.append(info) ret.data = course_list except Exception as e: ret.code = 1002 ret.error = "获取失败" return Response(ret.dict)
def update(self, request, *args, **kwargs): """ 修改用户选中的价格策略 :param request: :param args: :param kwargs: :return: """ response = BaseResponse() try: course_id = request.data.get('courseid') policy_id = str(request.data.get('policyid')) if request.data.get( 'policyid') else None key = settings.LUFFY_SHOPPING_CAR % ( USER_ID, course_id, ) if not CONN.exists(key): response.code = 10007 response.error = '课程不存在' return Response(response.dict) price_policy_dict = json.loads( CONN.hget(key, 'price_policy_dict').decode('utf-8')) if policy_id not in price_policy_dict: response.code = 10008 response.error = '价格策略不存在' return Response(response.dict) CONN.hset(key, 'default_price_id', policy_id) CONN.expire(key, 10 * 60) response.data = '修改成功' except Exception as e: response.code = 10006 response.error = '修改失败' return Response(response.dict)
def get(self, request, *args, pk, **kwargs): #第一阶段 # course = models.Course.objects.filter(id = pk).first() # print(course) #对象,也可以直接用get取 # ser = CourseSerializer(course) #只有单个对象 # return Response(ser.data) # 第二阶段 # ret = BaseResponse() # try: # course_obj = models.Course.objects.filter(id=pk).first() # ser = CourseSerializer(course_obj) # ret.data = ser.data # except Exception: # ret.data = 500 # ret.error = "获取数据失败" # return Response(ret.dict) #第三阶段 ret = BaseResponse() try: course_obj = models.Course.objects.get(id=pk) print(course_obj) ser = CourseModelSerializer(course_obj) print(ser) ret.data = ser.data except Exception: ret.code = 500 ret.error = "获取数据失败" return Response(ret.data)
def get(self, request, *args, **kwargs): res = BaseResponse() try: # 1 取到user_id user_id = request.user.id # 2 拼接购物车的key account_key = settings.ACCOUNT_KEY % (user_id, "*") # shopping_car_1_* # shopping_car_1_asdgnlaksdj # 3 去redis读取该用户的所有加入购物车的课程 # 3.1 先去模糊匹配出所有符合要求的key all_keys = REDIS_CONN.scan_iter(account_key) # 3.2 循环所有的keys 得到每个可以 account_course_list = [] for key in all_keys: account_course = json.loads(REDIS_CONN.get(key)) account_course_list.append(account_course) global_coupons = json.loads( REDIS_CONN.get("global_coupon_%s" % request.user.pk)) total_price = REDIS_CONN.get("total_price") res.data = { "account_course_list": account_course_list, "total": len(account_course_list), "global_coupons": global_coupons, "total_price": total_price } except Exception as e: res.code = 1033 res.error = "获取购物车失败" return Response(res.dict)
def post(self): rets = self.ftpop.check() if rets: api_abort(httpcode=400, errcode=4025, key=rets) self.parser.parse_args() orgin_data = request.json ftp_user = orgin_data.get("ftp_user") if ftp_user == "": return api_abort(errcode=4012) orgin_data["ftp_passwd"] = orgin_data.get( "ftp_passwd") or getRandomString() orgin_data["ftp_path"] = orgin_data.get( "ftp_path") or f'{www_path}/{ftp_user}' orgin_data["note"] = orgin_data.get("note") or ftp_user parms = {"ftp_user": ftp_user} check(Ftp, extra=parms, obj_path=orgin_data["ftp_path"]) create_dict = { "ftp_user": ftp_user, "ftp_passwd": orgin_data.get("ftp_passwd"), "ftp_path": orgin_data.get("ftp_path") } # 创建FTP站点 self.ftpop.create_ftp(**create_dict) ftpobj = Ftp(**orgin_data) ftpobj.add() res = BaseResponse() res.data = ftpobj.to_json() return res.dict
def put(self, request): res = BaseResponse() try: # 1 获取course_id和price_policy_id course_id = request.data.get('course_id') price_policy_id = request.data.get('price_policy_id') user_id = request.user.id # 2 校验数据的合法性 # 2.1 校验course_id是否合法 shoppingcart_key = settings.SHOPPINGCART_KEY%(user_id,course_id) if not cache.exists(shoppingcart_key): res.code = 1035 res.error = '课程不存在' return Response(res.dict) # 2.2 判断价格策略是否合法 course_info = json.loads(cache.get(shoppingcart_key)) price_policy_dict = course_info['relate_price_policy'] if str(price_policy_id) not in price_policy_dict: res.code = 1036 res.error = '所选的价格策略不存在' return Response(res.dict) # 3 修改redis中的default_policy_id course_info['choose_price_policy_id'] = price_policy_id # 4 修改信息后写入redis cache.set(shoppingcart_key,json.dumps(course_info)) res.data = '更新成功' except Exception as e: res.code = 1034 res.error = '更新价格策略失败' return Response(res.dict)
def get(self, request): res = BaseResponse() try: # 1 取到user_id user_id = request.user.id # 2 拼接购物车的key shopping_car_key = settings.SHOPPING_CAR_KEY % (user_id, "*") print("shopping_car_key", shopping_car_key) # shopping_car_1_* # shopping_car_1_asdgnlaksdj # 3 去redis读取该用户的所有加入购物车的课程 # 3.1 先去模糊匹配出所有符合要求的key all_keys = REDIS_CONN.keys(shopping_car_key) print("all_keys", all_keys) # 3.2 循环所有的keys 得到每个可以 shopping_car_list = [] for key in all_keys: print("key", key) course_info = json.loads(REDIS_CONN.get(key)) shopping_car_list.append(course_info) res.data = { "shopping_car_list": shopping_car_list, "total": len(shopping_car_list) } except Exception as e: res.code = 1033 res.error = "获取购物车失败" print("res.dict", res.dict) return Response(res.dict)
def list(self, request, *args, **kwargs): response = BaseResponse() try: shopping_car_list = [] # 'shopping_car_%s_%s' pattern = settings.LUFFY_SHOPPING_CAR % (1, '*') # 查询当前用户的所有的课程 shopping_list = CONN.keys(pattern) for key in shopping_list: tamp = { 'id': CONN.hget(key, 'id').decode('utf-8'), 'name': CONN.hget(key, 'name').decode('utf-8'), 'img': CONN.hget(key, 'img').decode('utf-8'), 'default_price_id': CONN.hget(key, 'default_price_id').decode('utf-8'), 'price_policy_dict': json.loads( CONN.hget(key, 'price_policy_dict').decode('utf-8')), } shopping_car_list.append(tamp) response.code = 200 response.data = shopping_car_list # print(shopping_car_list) except Exception as e: response.code = 4004 response.error = '查询购物车失败' return Response(response.dict)
def get(self, request, *args, **kwargs): ret = BaseResponse() try: # 从数据库获取数据 # 防止出现UnorderedObjectListWarning: Pagination may yield... queryset = models.DegreeCourse.objects.all() print(queryset) # 分页 page = PageNumberPagination() course_list = page.paginate_queryset(queryset, request, self) # 分页之后的结果执行序列化 ser = DegreeCourseTeachersModelSerializer(instance=course_list, many=True) print(ser.data) ret.data = ser.data except Exception as e: print(e) ret.code = 500 ret.error = '获取数据失败' return Response(ret.dict)
def get(self, request, pk, *args, **kwargs): ret = BaseResponse() res = {} try: courses_obj = models.Course.objects.filter( pk=pk, degree_course__isnull=False).first() print(courses_obj) res['name'] = courses_obj.name res['brief'] = courses_obj.brief res['level'] = courses_obj.get_level_display() res['hours'] = courses_obj.coursedetail.hours res['why_study'] = courses_obj.coursedetail.why_study name_list = courses_obj.coursedetail.recommend_courses.all() list = [] for i in name_list: print('___>', i.name) list.append(i.name) res['name_list'] = list print(res) ret.data = res print(ret.dict) except Exception as e: ret.code = 500 ret.error = '获取数据失败' return Response(ret.dict)
def get(self, request, *args, **kwargs): res = BaseResponse() order_list = Order.objects.filter( account=request.user).order_by("-date") data = [] for order in order_list: data.append({ "order_number": order.order_number, "date": order.date.strftime("%Y-%m-%d %H:%M:%S"), "status": order.get_status_display(), "actual_amount": order.actual_amount, "orderdetail_list": [{ "original_price": obj.original_price, "price": obj.price, "course_name": obj.content_object.name, "valid_period_display": obj.valid_period_display, } for obj in order.orderdetail_set.all()] }) res.data = data return Response(res.dict)
def put(self, request): res = BaseResponse() try: # 1 获取前端传过来的course_id 以及price_policy_id course_id = request.data.get("course_id", "") price_policy_id = request.data.get("price_policy_id", "") user_id = request.user.id # 2 校验数据的合法性 # 2.1 校验course_id是否合法 shopping_car_key = settings.SHOPPINGCAR_REDIS_KEY % (user_id, course_id) if not cache.exists(shopping_car_key): res.code = 1035 res.error = "课程不存在" return Response(res.dict) # 2.2 判断价格策略是否合法 course_info = cache.hgetall(shopping_car_key) price_policy_dict = json.loads(course_info["price_policy_dict"]) if str(price_policy_id) not in price_policy_dict: res.code = 1036 res.error = "所选的价格策略不存在" return Response(res.dict) # 3 修改redis中的default_policy_id course_info["default_policy_id"] = price_policy_id # 4 修改信息后写入redis cache.hmset(shopping_car_key, course_info) res.data = "更新成功" except Exception as e: res.code = 1034 res.error = "更新价格策略失败" return Response(res.dict)
def update(self, request, *args, **kwargs): response = BaseResponse() try: course_id = request.data.get('course_id') policy_id = str(request.data.get("price_policy_id") ) if request.data.get("price_policy_id") else None # print(policy_id) # policy_id = 2 key = settings.SHOPPING_CAR_KEY % (request.user.pk, course_id) # print(key) if not redis.exists(key): response.code = 1007 response.error = "课程不存在" return Response(response.dict) price_policy_dict = json.loads( redis.hget(key, 'price_policy_dict').decode('utf-8')) # print(price_policy_dict) if policy_id not in price_policy_dict: response.code = 1008 response.error = "价格周期不存在" return Response(response.dict) redis.hset(key, "default_price_policy_id", policy_id) response.data = "修改成功" return Response(response.dict) except Exception as e: response.code = 1009 response.error = str(e) print(e) return Response(response.dict)
def update(self, request, *args, **kwargs): response = BaseResponse() try: courseid = request.data.get('courseid') price = request.data.get('policyid') policyid = str(price) if price else None key = 'shopping_car_%s_%s' % (USER_ID, courseid) if not CONN.exists(key): response.code = 10003 response.error = '要修改的课程不存在' return Response(response.dict) print(CONN.hget(key, "price_policy_dict")) price_policy_dict = json.loads(CONN.hget( key, "price_policy_dict")) # 3.6支持bytes反序列化 if policyid not in price_policy_dict: response.code = 10004 response.error = '价格策略不存在' return Response(response.dict) CONN.hset(key, 'selected_price_id', policyid) response.code = 10000 response.data = '修改商品信息成功' except Exception as e: print(e) response.code = 100010 response.error = '修改商品数据失败' return Response(response.dict)
def list(self, request, *args, **kwargs): response = BaseResponse() try: shopping_car_key = settings.SHOPPING_CAR_KEY % (request.user.pk, '*') shopping_car_list = redis.keys(shopping_car_key) # print('hahahah',shopping_car_list) shopping_car_course_list = [] for key in shopping_car_list: tem = { # "id": redis.hget(key, 'id'), "name": redis.hget(key, 'name').decode('utf-8'), 'course_img': redis.hget(key, 'course_img').decode('utf-8'), 'price_policy_dict': json.loads( redis.hget(key, 'price_policy_dict').decode('utf-8')), "default_price_policy_id": redis.hget(key, "default_price_policy_id").decode('utf-8') } shopping_car_course_list.append(tem) response.data = shopping_car_course_list except Exception as e: response.code = 1005 response.error = '数据调取失败' print(response.dict) return Response(response.dict)
def update(self, request, *args, **kwargs): response = BaseResponse() try: course_id = request.data.get('courseid') policy_id = str(request.data.get('policyid')) if request.data.get( 'policyid') else None key = settings.LUFFY_SHOPPING_CAR % ( USER_ID, course_id, ) if not CONN.exists(key): response.code = 500 response.error = '课程不存在' return Response(response.dict) price_policy_dict = json.loads( CONN.hget(key, 'price_policy_dict').decode('utf-8')) if policy_id not in price_policy_dict: response.code = 502 response.error = '价格策略不存在' return Response(response.dict) CONN.hset(key, 'default_price_id', policy_id) # CONN.expire(key, 20 * 60) # 定时清除redis中的缓存数据 response.data = '修改成功' except Exception as e: response.code = 509 response.error = '修改失败' return Response(response.dict)
def list(self, request, *args, **kwargs): ret = BaseResponse() shopping_car_course_list = [] # pattern = "shopping_car_%s_*" % (USER_ID,) pattern = settings.LUFFY_SHOPPING_CAR % ( 1, '*', ) user_key_list = CONN.keys(pattern) for key in user_key_list: temp = { 'id': CONN.hget(key, 'id').decode('utf-8'), 'name': CONN.hget(key, 'name').decode('utf-8'), 'img': CONN.hget(key, 'img').decode('utf-8'), 'default_price_id': CONN.hget(key, 'default_price_id').decode('utf-8'), 'price_policy_dict': json.loads( CONN.hget(key, 'price_policy_dict').decode('utf-8')) } shopping_car_course_list.append(temp) ret.data = shopping_car_course_list return Response(ret.dict)