def send_sms_code( self,mobile, sms_code): try: result = CCP().send_template_sms(mobile, [sms_code, YUNTONGXUN_EXPIRE_TIME], 1) if result != 0: raise Exception('下单失败') except Exception as exc: logger.error(exc) raise self.retry(exc=exc,max_retries=3)
def send_verify_email(self,subject,message,from_email,recipient_list,html_message): try: send_mail(subject=subject, message=message, from_email=from_email, recipient_list=recipient_list, html_message=html_message) except Exception as exc: logger.error(exc) raise self.retry(exc=exc,max_retries=3)
def check_openid_token(token): # 1.创建实例 s = Serializer(secret_key=settings.SECRET_KEY, expires_in=constants.OPENID_TOKEN_EXPIRES_TIME) # 2.解密 解密的时候捕获异常 try: result = s.loads(token) except BadData as e: logger.error(e) return None # 获得解密后的数据 return result.get('openid')
def get(self, request, category_id, page_num): """提供商品列表页""" # 判断category_id是否正确 try: category = GoodsCategory.objects.get(pk=category_id) except GoodsCategory.DoesNotExist: return http.HttpResponseBadRequest('GoodsCategory does not exist') # 接收sort参数:如果用户不传,就是默认的排序规则 sort = request.GET.get('sort', 'default') # 查询商品频道分类 categories = get_categories() # 查询面包屑导航 breadcrumb = get_breadcrumb(category) # 按照排序规则查询该分类商品SKU信息 if sort == 'price': # 按照价格由低到高 sort_field = 'price' elif sort == 'hot': # 按照销量由高到低 sort_field = '-sales' else: # 'price'和'sales'以外的所有排序方式都归为'default' sort = 'default' sort_field = 'create_time' skus = SKU.objects.filter(category=category, is_launched=True).order_by(sort_field) # 创建分页器:每页N条记录 paginator = Paginator(skus, 5) # 获取每页商品数据 try: page_skus = paginator.page(page_num) except Exception as e: logger.error(e) # 如果page_num不正确,默认给用户404 return http.HttpResponseNotFound('empty page') # 获取列表页总页数 total_page = paginator.num_pages # 渲染页面 context = { 'categories': categories, # 频道分类 'breadcrumb': breadcrumb, # 面包屑导航 'sort': sort, # 排序字段 'category': category, # 第三级分类 'page_skus': page_skus, # 分页后数据 'total_page': total_page, # 总页数 'page_num': page_num, # 当前页码 } return render(request, 'list.html', context=context)
def put(self, request, address_id): json_dict = json.loads(request.body.decode()) receiver = json_dict.get('receiver') province_id = json_dict.get('province_id') city_id = json_dict.get('city_id') district_id = json_dict.get('district_id') place = json_dict.get('place') mobile = json_dict.get('mobile') tel = json_dict.get('tel') email = json_dict.get('email') # 2.根据传递过来的更新指定的地址信息 # address = Address.objects.get(pk=address_id) # address.recever=data.get('recever') # 3.更新 try: # 更新成功之后,返回 1 表示更新成功 # 返回 0 表示更新失败 Address.objects.filter(pk=address_id).update( user=request.user, title=receiver, receiver=receiver, province_id=province_id, city_id=city_id, district_id=district_id, place=place, mobile=mobile, tel=tel, email=email) # 再次查询一下地址信息 address = Address.objects.get(pk=address_id) except Exception as e: logger.error(e) return http.JsonResponse({'code': RETCODE.DBERR}) # 4.返回相应 address_dict = { "id": address.id, "title": address.title, "receiver": address.receiver, "province": address.province.name, "city": address.city.name, "district": address.district.name, "place": address.place, "mobile": address.mobile, "tel": address.tel, "email": address.email } return http.JsonResponse({'address': address_dict, 'code': RETCODE.OK})
def get(self, request): # 获取用户信息 user = request.user # 查询地址信息 try: addresses = Address.objects.filter(user=user, is_deleted=False) except Exception as e: logger.error(e) return http.HttpResponseBadRequest('未找到数据') # 链接redis redis_conn = get_redis_connection('carts') # hash sku_id_count = redis_conn.hgetall('carts_%s' % user.id) # set ids = redis_conn.smembers('selected_%s' % user.id) # 取出的商品是base类型,要进行强制转换为int类型 selected_carts = {} for id in ids: selected_carts[int(id)] = int(sku_id_count[id]) # 获取商品的id, 根据商品id查询商品信息[sku, sku] ids = selected_carts.keys() # pk__in 表示查询在ids中的数据 skus = SKU.objects.filter(pk__in=ids) # 对象商品列表进行遍历 total_count = 0 # 总数量 # 导入货比类型 from decimal import Decimal total_amount = Decimal('0') # 总金额 for sku in skus: # 8.遍历的过程中 对sku添加数量和对应商品的总金额 sku.count = selected_carts[sku.id] # 数量小计 sku.amount = sku.count * sku.price # 金额小计 # 也去计算当前订单的总数量和总金额 total_count += sku.count total_amount += sku.amount # 再添加一个运费信息 freight = Decimal('10.00') context = { 'addresses': addresses, 'skus': skus, 'total_count': total_count, 'total_amount': total_amount, 'freight': freight, 'payment_amount': total_amount + freight } return render(request, 'place_order.html', context=context)
def post(self, request): #0 判断用户的地址数量是否超过20个 count = Address.objects.filter(user=request.user, is_deleted=False).count() if count > 20: return http.JsonResponse({ 'code': RETCODE.THROTTLINGERR, 'errmsg': '个数超过上限' }) # 1.判断当前用户是否登陆 # if request.user.is_authenticated # 2.接收参数 json_dict = json.loads(request.body.decode()) receiver = json_dict.get('receiver') province_id = json_dict.get('province_id') city_id = json_dict.get('city_id') district_id = json_dict.get('district_id') place = json_dict.get('place') mobile = json_dict.get('mobile') tel = json_dict.get('tel') email = json_dict.get('email') # 校验参数 if not all( [receiver, province_id, city_id, district_id, place, mobile]): return http.HttpResponseBadRequest('缺少必传参数') if not re.match(r'^1[3-9]\d{9}$', mobile): return http.HttpResponseBadRequest('参数mobile有误') if tel: if not re.match( r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel): return http.HttpResponseBadRequest('参数tel有误') if email: if not re.match( r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): return http.HttpResponseBadRequest('参数email有误') # 4.数据入库 try: address = Address.objects.create(user=request.user, title=receiver, receiver=receiver, province_id=province_id, city_id=city_id, district_id=district_id, place=place, mobile=mobile, tel=tel, email=email) # 如果没有默认地址我们就设置一个默认地址 if not request.user.default_address: request.user.default_address = address request.user.save() except Exception as e: logger.error(e) return http.JsonResponse({ 'code': RETCODE.DBERR, 'errmsg': '数据库操作失败' }) # 5.返回相应 # 新增地址成功,将新增的地址响应给前端实现局部刷新 address_dict = { "id": address.id, "title": address.title, "receiver": address.receiver, "province": address.province.name, "city": address.city.name, "district": address.district.name, "place": address.place, "mobile": address.mobile, "tel": address.tel, "email": address.email } return http.JsonResponse({ 'code': RETCODE.OK, 'errmsg': 'ok', 'address': address_dict })
def put(self, request): #email = request.GET.get('email') body = request.body body_str = body.decode() data = json.loads(body_str) email = data.get("email") if not all([email]): return http.JsonResponse({ 'code': RETCODE.PARAMERR, 'errmsg': '参数错误' }) if not re.match( r'^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$', email): return http.JsonResponse({ 'code': RETCODE.PARAMERR, 'errmsg': '参数错误' }) if not request.user.is_authenticated(): return http.JsonResponse({ 'code': RETCODE.SESSIONERR, 'errmsg': '未登录' }) #更新数据 try: request.user.email = email request.user.save() except Exception as e: logger.error(e) return http.HttpResponse({'code': RETCODE.DBERR, 'ermsg': '更新错误'}) #发送激活邮件 from django.core.mail import send_mail subject = '主题' message = 'message' recipient_list = [email] from_email = '*****@*****.**' html_message = "<a href='#'>戳我,戳我,戳我有惊喜</a>" #将代码换成异步代码 # send_mail( # subject= subject, # message = html_message, # recipient_list=recipient_list, # from_email = from_email # ) verify_url = generic_verify_email_url(request.user.id) html_message = '<p>尊敬的用户您好!</p>' \ '<p>感谢您使用美多商城。</p>' \ '<p>您的邮箱为:%s 。请点击此链接激活您的邮箱:</p>' \ '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url) from celery_tasks.email.tasks import send_verify_email send_verify_email.delay(subject=subject, message=message, recipient_list=recipient_list, from_email=from_email, html_message=html_message) #返回响应 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})