第一步:定义用于保存邮箱信息的视图,由于需要用户登录之后才能添加邮箱,所以在前后端交互时要先进行用户登录状态的验证(因会过期),数据交互使用json。
在xiaoyumall/utils下创建views.py,并定义限制用户访问类LoginRequiredJSONMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from xiaoyu_mall.utils.response_code import RETCODE
from django.http import JsonResponse
class LoginRequiredJSONMixin(LoginRequiredMixin):
"""自定义判断用户是否登录的扩展类:返回JSON"""
# 'ensure_ascii': False 错误信息以中文形式显示
def handle_no_permission(self):
resp_json = {'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'}
print(resp_json)
return JsonResponse(resp_json, json_dumps_params={'ensure_ascii': False})
继承这个类即可实现登录状态的验证。
import json
from xiaoyu_mall.utils.views import LoginRequiredJSONMixin
logger = logging.getLogger('django')
class EmailView(LoginRequiredJSONMixin, View):
"""添加邮箱"""
def put(self, request):
"""实现添加邮箱逻辑"""
# 接收参数 body, 类型是bytes类型
json_str = request.body.decode()
json_dict = json.loads(json_str)
email = json_dict.get('email')
# print(email)
if not email: # 校验参数
return HttpResponseForbidden('缺少email参数')
if not re.match(
r'^[a-z0-9][\w\\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
return HttpResponseForbidden('参数email有误')
# 赋值email字段
try:
request.user.email = email
request.user.save()
except Exception as e:
logger.error(e)
return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'})
# 响应添加邮箱结果
# 响应添加邮箱结果
return JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})
第二步:定义路由
path('emails/', views.EmailView.as_view()),
第三步:调整session时长,验证。