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') # 校验参数 if not all([receiver, province_id, city_id, district_id, place, mobile]): return http.HttpResponseForbidden('缺少必传参数') if not re.match(r'^1[3-9]\d{9}$', mobile): return http.HttpResponseForbidden('参数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.HttpResponseForbidden('参数tel有误') if email: if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): return http.HttpResponseForbidden('参数email有误') # 判断地址是否存在,并更新地址信息 try: Address.objects.filter(id=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 ) except Exception as e: logger.error(e) return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'}) # 构造响应数据 address = Address.objects.get(id=address_id) 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': '更新地址成功', 'address': address_dict})
def send_verify_email(self, to_email, verify_url): """ bind:保证task对象会作为第一个参数自动传入 name:异步任务别名 retry_backoff:异常自动重试的时间间隔 第n次(retry_backoff×2^(n-1))s max_retries:异常自动重试次数的上限 """ # send_mail(subject, message, from_email, recipient_list, # fail_silently=False, auth_user=None, auth_password=None, # connection=None, html_message=None): subject = "美多商城邮箱验证" from_email = settings.EMAIL_FROM recipient_list = [to_email] html_message = '<p>尊敬的用户您好!</p>' \ '<p>感谢您使用美多商城。</p>' \ '<p>您的邮箱为:%s 。请点击此链接激活您的邮箱:</p>' \ '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url) try: send_mail(subject=subject, message='', from_email=from_email, recipient_list=recipient_list, html_message=html_message) except Exception as e: logger.error(e) # 有异常自动重试三次 raise self.retry(exc=e, max_retries=3)
def get(self, request): # 得到回传的 code code = request.GET.get('code') oauth_sina = APIClient(app_key=settings.SINA_APP_KEY, app_secret=settings.SINA_APP_SECRET, redirect_uri=settings.SINA_REDIRECT_URI) try: # 根据 code 得到 tocken => {'access_token': '2.00IsO_OGJcPibD120f9a82d9R4xf1C', 'uid': '5708251100', 'expires_in': 1563044399, 'expires': 1563044399} tocken = oauth_sina.request_access_token(code=code) except Exception as e: logger.error(e) return http.HttpResponseServerError('Oauth2.0认证失败!') # 获取 uid uid = tocken.get('uid') # 判断 uid 是否绑定用户 try: sina_user = OAuthSinaUser.objects.get(uid=uid) except Exception as e: # 查询失败说明未绑定,跳转到绑定页面 # 将 uid 加密 secret_uid = SecretOauth().dumps({'uid': uid}) context = {'uid': secret_uid} return render(request, 'sina_callback.html', context) else: # 用户已绑定,则记录用户登陆状态 user = sina_user.user login(request, user) # 跳转到首页 response = redirect(reverse('contents:index')) # 设置 cookie response.set_cookie('username', user.username, max_age=3600 * 24 * 14) return response
def put(self, request): """实现添加邮箱逻辑""" # 接收参数 json_str = request.body.decode() json_dict = json.loads(json_str) email = json_dict.get('email') # 校验参数 if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): return http.HttpResponseForbidden('参数email有误') # 赋值email字段 try: request.user.email = email request.user.save() # 保存邮箱成功之后 发送邮件---网易发送---耗时任务 verify_url = generate_verify_emails_url(request.user) from celery_tasks.email.tasks import send_verify_email send_verify_email.delay(email, verify_url) except Exception as e: logger.error(e) return http.JsonResponse({ 'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败' }) # 响应添加邮箱结果 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})
def send_verify_email(self, to_email, verify_url): """ subject :主题标题 message :邮件内容 from_email:发件人 recipient_list:收件人列表 html_message: html标签邮件内容 """ subject = "美多商城邮箱验证" message = "" from_email = settings.EMAIL_FROM recipient_list = [to_email] html_message = '<p>尊敬的用户您好!</p>' \ '<p>感谢您使用美多商城。</p>' \ '<p>您的邮箱为:%s 。请点击此链接激活您的邮箱:</p>' \ '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url) try: # 发邮件djano提供 send_mail(subject, message, from_email, recipient_list, html_message=html_message) except Exception as e: logger.error(e) print("邮箱任务已经触发")
def get(self, request): """实现邮箱验证逻辑""" # 接受token token = request.GET.get('token') # 2.解密 3. 取数据库对比 # 校验参数 # 判断token是否为空和过期,提取user if not token: return http.HttpResponseBadRequest('缺少token') # 验证token并提取user user = check_verify_email_token(token) if not user: return http.HttpResponseForbidden('无效的token') # 4. 改email_active try: user.email_active = True user.save() except Exception as e: logger.error(e) return http.HttpResponseServerError('激活邮件失败') # 5.重定向到 用户中心 return redirect(reverse('users:info'))
def put(request): # 非表单提交方式 # PUT提交方式 --- 是将数据放到 request.body 的 bytes 数据 # 需要现转码成json的字符串,然后转成字典来提取 json_str = request.body json_dict = json.loads(json_str) email = json_dict['email'] if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): return http.HttpResponseForbidden('参数email有误') request.user.email = email try: request.user.save() except Exception as e: logger.error(e) return http.JsonResponse({ 'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败' }) # 发送邮件 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})
def put(self,request): #取出请求参数中的email json_str = request.body.decode() json_dict = json.loads(json_str) email = json_dict.get('email') #校验email格式是否满足要求 # if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): # return http.HttpResponseForbidden('参数email有误') #保存email try : request.user.email = email request.user.save() except Exception as e: logger.error(e) return http.JsonResponse({'code': RETCODE.DBERR,'errmsg':'添加邮箱失败'}) token_value = { 'user_id': request.user.id, 'email': email } from utils.secret import SecretOauth secret_str = SecretOauth().dumps(token_value) verify_url = settings.EMAIL_ACTIVE_URL + "?token=" + secret_str from celery_tasks.email.tasks import send_verify_email send_verify_email.delay(email, verify_url) # 4. 返回前端结果 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})
def is_bind_openid(request, openid): # 如果绑定了 try: oauth_user = OAuthQQUser.objects.get(openid=openid) except Exception as e: logger.error(e) # 没有绑定了-->重定向到绑定页面 secret_openid = SecretOauth().dumps({'openid': openid}) context = { 'openid': secret_openid } return render(request, 'oauth_callback.html', context) else: # 绑定了-保持登录状态->重定向到首页-->设置cookie username qq_user = oauth_user.user login(request, qq_user) # 响应结果 response = redirect(reverse('contents:index')) # 登录时用户名写入到cookie,有效期15天 response.set_cookie('username', qq_user.username, constants.USERNAME_EXPIRE_TIME) return response
def get(self, request): code = request.GET.get("code") if not code: return http.HttpResponseForbidden('缺少code') oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=None) try: accss_token = oauth.get_access_token(code) openid = oauth.get_open_id(accss_token) except Exception as e: logger.error(e) return http.HttpResponseServerError('OAuth2.0认证失败') try: oauth_user = OAuthQQUser.objects.get(openid=openid) except Exception as e: # context = {"openid": openid} return render(request, 'oauth_callback.html', context) else: qq_user = oauth_user.user login(request, qq_user) # 重定向到主页 response = redirect(reverse('users:index')) # 登录时用户名写入到cookie,有效期15天 response.set_cookie('username', qq_user.username, max_age=3600 * 24 * 15) return response
def get(self, request, mobile): # 接收参数 sms_code = request.GET.get("sms_code") # 校验参数 try: user = User.objects.get(mobile=mobile) except Exception as e: logger.error(e) return http.JsonResponse({ "status": 5004, "user_id": None, "access_token": None }) # 判断手机验证码是否正确 # 链接redis数据库 client = get_redis_connection("sms_code") sms_redis_code = client.get("sms_%s" % mobile) if sms_redis_code.decode() != sms_code: return http.JsonResponse({ "status": 5001, "user_id": None, "access_token": None }) return http.JsonResponse({ "status": 5000, "user_id": user.id, "access_token": "abc" })
def post(self, request, user_id): # 接收参数 json_str = request.body.decode() import json json_dict = json.loads(json_str) password = json_dict.get("password") password2 = json_dict.get("password2") access_token = json_dict.get("access_token") # 校验参数 try: user = User.objects.get(id=user_id) except Exception as e: logger.error(e) return http.JsonResponse({"status": 5002, 'message': "没有该用户!"}) # 校验密码是否一致 # 正则校验 if password != password2: return http.HttpResponseForbidden("密码不一致") user.set_password(raw_password=password) user.save() return http.JsonResponse({"status": 500, 'message': "成功修改密码!"})
def post(self, request, category_id): # print(category_id) try: category = GoodsCategory.objects.get(id=category_id) except Exception as e: logger.error(e) return http.HttpResponseNotFound('缺少必传参数') # # 用strftime将日期按照格式转化为字符串 # time_str = datetime.now().strftime("%Y-%m-%d") # # 用strptime将字符串按照日期格式在转换成日期形式 # time_date = datetime.strptime(time_str,"%Y-%m-%d") # 将日期按照格式转换成字符串 today_str = datetime.now().strftime('%Y-%m-%d') # 将字符串再转换成日期格式 time_date = datetime.strptime(today_str, '%Y-%m-%d') try: count_data = category.goodsvisitcount_set.get(date=time_date) except: count_data = GoodsVisitCount() try: count_data.count += 1 count_data.category = category count_data.save() except: return http.HttpResponseServerError('新增失败') return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
def get(self, request, mobile): # 接受参数 access_token = request.GET.get("access_token") # 校验参数 try: user = User.objects.get(mobile=mobile) except Exception as e: logger.error(e) return http.HttpResponseForbidden("手机号不存在") if access_token != "abc": return http.JsonResponse({"status": 5001, 'message': "token有误!"}) # 设计6位随机的短信验证码 sms_code = randint(100000, 999999) # 存到redis的数据库中 redis_client = get_redis_connection("sms_code") redis_client.setex("sms_%s" % mobile, 300, sms_code) # # 使用荣连云发短信 # from libs.yuntongxun.sms import CCP # CCP().send_template_sms(mobile, [sms_code, 5], 1) # print("短信验证码是:"+str(sms_code)) # 6. 发短信--容联云 # from libs.yuntongxun.sms import CCP # # 手机号 6位码 过期时间分钟 短信模板 # CCP().send_template_sms("mobile", [sms_code, 5], 1) print("短信验证码是:" + str(sms_code)) return http.JsonResponse({"status": 5000, 'message': "短信发送成功"})
def post(self, request): old_password = request.POST.get('old_pwd') new_password = request.POST.get('new_pwd') new_password2 = request.POST.get('new_cpwd') if not all([old_password, new_password, new_password2]): return http.HttpResponseForbidden('缺少必传参数') #检查旧密码是否正确 result = request.user.check_password(old_password) if not result: logger.error(e) return render(request, 'user_center_pass.html', {'origin_pwd_errmsg': '原始密码错误'}) if new_password != new_password2: return http.HttpResponseForbidden('两次输入的密码不一致') try: request.user.set_password(new_password) request.user.save() except Exception as e: logger.error(e) return render(request, 'user_center_pass.html', {'change_pwd_errmsg': '修改密码失败'}) # 清理状态保持信息 logout(request) response = redirect(reverse('users:login')) response.delete_cookie('username') # # 响应密码修改结果:重定向到登录界面 return response
def put(self, request): json_str = request.body.decode() # print(json_str) import json json_dict = json.loads(json_str) email = json_dict.get('email') # print(request.user) # print(email) # username= json_dict.get("username") # print(username) # request.user.email= email # request.user.save() # 校验 if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): return http.HttpResponseForbidden('参数email有误') # 1.加密的数据 data_dict = {'user_id': request.user.id, "email": request.user.email} # 2. 进行加密数据 secret_data = SecretOauth().dumps(data_dict) # 发送邮件 #subject 邮件标题 # message 普通邮件正文,普通字符串 # from_email 发件人 # recipient_list 收件人列表 # html_message 多媒体邮件正文,可以是html字符串 subject = "美多商城邮箱验证" # subject = "ai爱直播" verify_url = settings.EMAIL_VERIFY_URL + '?token=' + secret_data html_message = '<p>尊敬的用户您好!</p>' \ '<p>感谢您使用美多商城。</p>' \ '<p>您的邮箱为:%s 。请点击此链接激活您的邮箱:</p>' \ '<p><a href="%s">%s</a></p>' % (email,verify_url, verify_url) # html_message = '<p>尊敬的用户赵博您好!</p>' \ # '<p>感谢您的注册</p>' \ # '<p>您的邮箱为:%s 。请点击此链接激活您的邮箱:</p>' \ # '<p><a href="http://www.sharesome.com">点此进入</a></p>' % (email) send_mail(subject, message="1", from_email="*****@*****.**", recipient_list=[email], html_message=html_message) # 保存数据库中 try: User.objects.filter(username=request.user).update(email=email) except Exception as e: logger.error(e) return http.JsonResponse({ 'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败' }) return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})
def authenticate(self, request, username=None, password=None, **kwargs): # 判断是前台的访问还是后台的访问 if request == None: # 后台的访问 try: if re.match(r"^[0-9]{11}", username): user = User.objects.get(mobile=username) else: user = User.objects.get(username=username, is_staff=True) except Exception as e: logger.error(e) return None else: if user.check_password(password): return user else: user = None return user else: # 前台的访问 try: if re.match(r"^[0-9]{11}", username): user = User.objects.get(mobile=username) else: user = User.objects.get(username=username) except Exception as e: logger.error(e) else: if user.check_password(password): return user else: user = None return user
def post(self, request, category_id): # 获取当前商品 try: category = GoodsCategory.objects.get(id=category_id) except Exception as e: logger.error(e) return http.HttpResponseNotFound('缺少必传参数') # 查询日期数据 from datetime import datetime # 将日期格式转换为字符串 today_str = datetime.now().strftime('%Y-%m-%d') # 将字符串转换为日期 today_date = datetime.strptime(today_str, '%Y-%m-%d') try: # 如果有当天商品分类的数据 就直接增加数量 count_data = category.goodsvisitcount_set.get(date=today_date) except Exception as e: # 否则 新增一条记录 然后增加数量 count_data = GoodsVisitCount() # 增加数量 try: count_data.count += 1 count_data.category = category count_data.save() except Exception as e: logger.error(e) return http.HttpResponseServerError('新增失败') return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
def put(self,request): '''实现邮箱添加逻辑''' # 接收参数 json_str = request.body.decode() json_dict = json.loads(json_str) email = json_dict['email'] print("邮箱是:",email) # 校验参数 if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): return http.HttpResponseForbidden('参数email有误') # 赋值email字段 try: request.user.email = email request.user.save() except Exception as e: logger.error(e) return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'}) # 拼接url from apps.users.utils import generate_verify_email_url verify_url = generate_verify_email_url(request.user) # 4.异步发送邮件 from celery_tasks.email.tasks import send_verify_email send_verify_email.delay(email, verify_url) # 5.响应添加邮箱结果 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})
def post(self,request): #接受参数 old_password = request.POST.get('old_pwd') new_password = request.POST.get('new_pwd') new_password2 = request.POST.get('new_cpwd') if not all([old_password,new_password,new_password2]): return HttpResponseForbidden('缺少必传参数') try: request.user.check_password(old_password) except Exception as e: logger.error(e) return render(request,'user_center_pass.html',{'origin_pwd_errmsg':'原始密码错误'}) if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password): return HttpResponseForbidden('密码至少8位') if new_password != new_password2: return HttpResponseForbidden('两次输得密码不一致') # 3 修改密码 try: request.user.set_password(new_password) request.user.save() except Exception as e: logger.error(e) return HttpResponseForbidden('修改密码失败') #退出登录 logout(request) #重定向到登录页 response = redirect(render('users:login')) #清除cookie response.delete_cookie('username') return response
def post(self, request): # 接收参数 username = request.POST.get("username") password = request.POST.get("password") remembered = request.POST.get("remembered") # 校验 # 数据库查询 try: # django自带的认证方法 from django.contrib.auth import authenticate user = authenticate(request, username=username, password=password) except User.DoesNotExist as e: logger.error(e) return http.HttpResponseForbidden("查无此人") # 修改最后登录时间为今天 try: from datetime import date user.last_login = date.today() user.save() except Exception as e: logger.error(e) # 判断是否记住登陆 if remembered == "on": request.session.set_expiry(None) else: request.session.set_expiry(0) # 判断用户是否存在 if user is None: return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'}) else: # 设置session login(request, user) next = request.GET.get("next") if next: response = redirect(next) response.set_cookie("username", user.username, max_age=3600 * 24 * 15) return response else: response = redirect(reverse("users:index")) # 设置cookie response.set_cookie("username", user.username, max_age=3600 * 24 * 15) # 合并购物车 from apps.carts.utils import merge_cart_cookie_to_redis merge_cart_cookie_to_redis(request, response) return response
def get(self, request, mobile): # 1.解析校验参数--mobile 不用校验 uuid = request.GET.get('image_code_id') image_code = request.GET.get('image_code') # 2.校验图形验证码 如果正确 发送验证码, 不正确 直接返回 # 2.1 根据uuid 去redis数据库查询 图片验证码 from django_redis import get_redis_connection image_redis_client = get_redis_connection('verify_image_code') redis_img_code = image_redis_client.get('img_%s' % uuid) # 判断服务器返回的验证 if redis_img_code is None: return http.HttpResponseForbidden('图形验证码失效了') # 如果有值 删除redis服务器上的图形验证码 try: image_redis_client.delete('img_%s' % uuid) except Exception as e: logger.error(e) # 2.2 和前端传过来的进行做对比 # 千万注意: 在redis取出来的是 bytes 类型不能直接做对比 decode() if image_code.lower() != redis_img_code.decode().lower(): return http.HttpResponseForbidden({'输入图形验证码有误'}) # 3.生成短信验证码,redis-存储 from random import randint sms_code = "%06d" % randint(0, 999999) sms_redis_client = get_redis_connection('sms_code') # 4.让第三方 容联云-给手机号-发送短信 # from libs.yuntongxun.sms import CCP # # 手机号 验证码 过期时间5分钟 ,类型默认1 # CCP().send_template_sms(mobile, [sms_code, 5], 1) # # CCP().send_template_sms(mobile, [sms_code, 5], 1) # print("当前验证码是:", sms_code) # 发送短信验证码 # CCP().send_template_sms(mobile,[sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], constants.SEND_SMS_TEMPLATE_ID) # Celery异步发送短信验证码 from celery_tasks.sms.tasks import ccp_send_sms_code ccp_send_sms_code.delay(mobile, sms_code) print("当前验证码是:", sms_code) # (异步发短信) # 管道 pipeline = sms_redis_client.pipeline() pipeline.setex("sms_%s" % mobile, 300, sms_code) pipeline.setex('send_flag%s' % mobile, 60, 1) pipeline.execute() # 获取redis里面的标识 send_sms_flag = sms_redis_client.get('send_flag%s' % mobile) if send_sms_flag: return http.HttpResponseForbidden({'发送短信过于频繁'}) # 如果 倒计时标识 不在 # 5.告诉前端短信发送完毕 return JsonResponse({'code': '0', 'errmsg': '发送短信成功'})
def get(self, request, category_id, page_num): # 判断有没有三级分类数据 try: category = GoodsCategory.objects.get(id=category_id) except Exception as e: logger.error(e) return http.HttpResponseNotFound('GoodsCategory does not exist') # 调用商品频道分类分数 categories = get_categories() # 调用面包屑导航 breadcrumb = get_breadcrumb(category) # 按照排序规则查询该分类商品SKU信息 # 获取用户的查询方式 sort = request.GET.get('sort', 'default') # 判断 if sort == 'price': sort_field = 'price' elif sort == 'hot': sort_field = '-sales' else: sort_field = 'create_time' # SKU信息排序 skus = SKU.objects.filter(category=category, is_launched=True).order_by(sort_field) # 分页 from django.core.paginator import Paginator # 实例化分页器 提供内容和分页的数 pagenator = Paginator(skus, constants.GOODS_LIST_LIMIT) # 获取总页数 total_page = pagenator.num_pages # 获取每页的数据 try: page_skus = pagenator.page(page_num) except Exception as e: logger.error(e) return http.HttpResponseNotFound('empty page') # 渲染页面 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)
def put(self,request,address_id): try: address = Address.objects.get(id=address_id) request.user.default_address = address request.user.save() except Exception as e: logger.error(e) return JsonResponse({'code':RETCODE.DBERR,'errmsg':'设置默认地址失败'}) return JsonResponse({'code':RETCODE.OK,'errmsg':'设置默认地址成功'})
def delete(self,request,address_id): try: address = Address.objects.get(id=address_id) address.is_deleted=True address.save() except Exception as e: logger.error(e) return JsonResponse({'code':RETCODE.DBERR,'errmsg':'删除地址失败'}) return JsonResponse({'code':RETCODE.OK,'errmsg':'删除地址成功'})
def get(self,request,mobile): # 接收uuid和用户输入的验证码 uuid = request.GET.get('image_code_id') image_code = request.GET.get('image_code') # 连接redis,根据uuid取出图片验证码 image_client_redis = get_redis_connection('verify_image_code') image_code_redis = image_client_redis.get('img_%s' % uuid) # 判None if image_code_redis is None: return http.JsonResponse({'code': "4001", 'errmsg': '图形验证码失效了'}) # 删除redis数据库中的uuid中的图片验证码 try: image_client_redis.delete('img_%s' % uuid) except Exception as e: logger.error(e) # 判断redis取出来的数据和用户输入的验证码是否相等 if image_code.lower() != image_code_redis.decode().lower(): return http.JsonResponse({'code': "4001", 'errmsg': '图形验证码有误'}) # 生成短信验证码 from random import randint sms_code = "%06d" % randint(0,999999) # 保存验证码到redis数据库 sms_client_redis = get_redis_connection('sms_code') # sms_client_redis.setex('sms_%s' % mobile ,300 ,sms_code) # 避免频繁发送短信验证码 send_flag = sms_client_redis.get('send_flag_%s' % mobile) if send_flag: return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'}) # 创建Redis管道 pl = sms_client_redis.pipeline() # 将Redis请求添加到队列 pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code) pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1) # 执行请求 pl.execute() # 使用第三方平台荣联云给手机号发短信 # from libs.yuntongxun.sms import CCP # CCP().send_template_sms(mobile,[sms_code,5],1) # Celery异步发送短信验证码 from celery_tasks.sms.tasks import ccp_send_sms_code ccp_send_sms_code.delay(mobile, sms_code) print("当前验证码是:",sms_code) print("手机号:",mobile) # 告诉前端 短信发送完毕 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功!'})
def get(self, request, sku_id): # 获取当前sku信息 try: sku = SKU.objects.get(id=sku_id) except Exception as e: logger.error(e) return render(request, '404.html') # 调用商品分类频道 categories = get_categories() # 调用面包屑组件 breadcrumb = get_breadcrumb(sku.category) # 构建当前商品的规格键 sku_specs = sku.specs.order_by('spec_id') sku_key = [] for spec in sku_specs: sku_key.append(spec.option.id) # 获取当前商品的所有SKU skus = sku.spu.sku_set.all() # 构建不同规格参数(选项)的sku字典 spec_sku_map = {} for s in skus: # 获取sku的规格参数 s_specs = s.specs.order_by('spec_id') # 用于形成规格参数-sku字典的键 key = [] for spec in s_specs: key.append(spec.option.id) # 向规格参数-sku字典添加记录 spec_sku_map[tuple(key)] = s.id # 获取当前商品的规格信息 goods_specs = sku.spu.specs.order_by('id') # 若当前sku的规格信息不完整,则不再继续 if len(sku_key) < len(goods_specs): return for index, spec in enumerate(goods_specs): # 复制当前sku的规格键 key = sku_key[:] # 该规格的选项 spec_options = spec.options.all() for option in spec_options: # 在规格参数sku字典中查找符合当前规格的sku key[index] = option.id option.sku_id = spec_sku_map.get(tuple(key)) spec.spec_options = spec_options # 渲染页面 context = { 'categories': categories, 'breadcrumb': breadcrumb, 'sku': sku, 'specs': goods_specs, } return render(request, 'detail.html', 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') #校验参数 if not all([receiver, province_id, city_id, district_id, place, mobile]): return HttpResponseForbidden('缺少必传参数') if not re.match(r'^1[3-9]\d{9}$', mobile): return HttpResponseForbidden('参数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 HttpResponseForbidden('参数tel有误') if email: if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): return HttpResponseForbidden('参数email有误') #判断 try: address = Address.objects.get(id=address_id) address.user = request.user address.title = receiver address.receiver = receiver address.province_id = province_id address.city_id = city_id address.district_id = district_id address.mobile = mobile address.place = place address.tel = tel address.email = email address.save() except Exception as e: logger.error(e) return JsonResponse({'code':RETCODE.DBERR,'errmsg':'更新地址失败'}) # 4 .构建前端需要的数据格式 address = Address.objects.get(id=address_id) address_dict = { 'id': address_id, 'title': address.receiver, 'receiver': address.receiver, 'province': address.province.name, 'city': address.city.name, 'district': address.district.name, 'mobile': address.mobile, 'place': address.place, 'tel': address.tel, 'email': address.email } #响应更新地址结果 return JsonResponse({'code':RETCODE.OK,'errmsg':'更新地址成功','address':address_dict})
def get(self, request, mobile): # * 2.1 接收图片验证码 image_code = request.GET.get('image_code') uuid = request.GET.get('image_code_id') # * 2.2 校验图片验证码的正确性--redis_image_code 一样; null 过期了, 不一致,写错了 try: img_redis_client = get_redis_connection('verify_image_code') redis_img_code = img_redis_client.get("img_%s" % uuid) if not redis_img_code: return JsonResponse({'code': "4001", 'errmsg': '图形验证码失效了'}) # 千万注意: redis返回的是 bytes 不能直接对比 bytes.decode() if redis_img_code.decode().lower() != image_code.lower(): return JsonResponse({'code': "4001", 'errmsg': '图形验证码错误!'}) # 删除以前的图片验证码 img_redis_client.delete("img_%s" % uuid) except Exception as e: logger.error(e) # 频繁发送短信验证码 sms_redis_client = get_redis_connection('sms_code') #1.取出 redis 保存发短信标识 send_flag = sms_redis_client.get('send_flag_%s' % mobile) import json if send_flag: ret = {'code': "4002", 'errmsg': '发送短信过于频繁'} # return JsonResponse({'code': "4002", 'errmsg': '发送短信过于频繁'},json_dumps_params={'ensure_ascii':False},content_type="application/json,charset=utf-8") return HttpResponse(json.dumps(ret,ensure_ascii=False),content_type="application/json,charset=utf-8") # * 2.3 生成短信验证码 6位 随机码 random.radint(0,999999) sms_code = '%06d' % random.randint(0, 999999) # * 2.4 redis存储 短信验证码 try: p1=sms_redis_client.pipeline() p1.setex('send_flag_%s' % mobile,constants.SMSCODE_SEND_TIME,1) p1.setex('sms_%s' % mobile,constants.SMSCODE_EXPIRE_TIME, sms_code) p1.execute() except Exception as e: logger.error(e) # * 2.5 容联云发送短信 # from libs.yuntongxun.sms import CCP # 手机号 验证码 过期时间 1短信模板 # CCP().send_template_sms(mobile,[sms_code,5],1) # print(sms_code) # * 2.5 容联云发送短信---celery异步发送 from celery_tasks.sms.tasks import send_sms_code send_sms_code.delay(mobile, sms_code) # * 2.6 发送短信完毕--让前端 倒计时 60秒 return JsonResponse({'code': '0', 'errmsg': '发送短信成功'},json_dumps_params={'ensure_ascii':False})
def redis_demo(): try: # 2.链接 # ''default -参数 ---dev配置文件配置的名字 client = get_redis_connection('default') # 3.增删改查 client.set('meiduo', 'shangcheng') except Exception as e: logger.error(e)