django注册内容

import random
import re

import jwt
import redis
from django.contrib.auth.hashers import check_password
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler

from api.models import User


class CheckUsername(APIView):
    def get(self,request,username):
        #验证用户名是否重复
        rule=r'^[a-zA-Z][a-zA-Z0-9]{5,15}$'

        match_rs=re.findall(rule,username)

        if not match_rs:
            return Response({
                "code": 400,
                "msg": '用户名错误'
            })
        user_count=User.objects.filter(username=username).count()
        if not user_count:
            return Response({
                "code":200,
                "msg":'username',
            })
        else:
            return  Response({
                "code":400,
                "msg":'用户名存在'
            })
class Checkmobile(APIView):
    def get(self,request,mobile):
        rule = r'1[3-9][0-9]{9}$'#
        match_rs=re.findall(rule,mobile)

        if not match_rs:
            return  Response({
            "code": 400,
            "msg": '手机号格式错误'
        })

        mobile_count=User.objects.filter(mobile=mobile).count

        if not mobile_count:
            return Response({
                "code":400,
                "msg":'手机号存在'
            })
        else:
            return  Response({
                "code":200,
                "msg":mobile
            })

# 验证码生成

class ImageCode(APIView):
    def get(self,request,uuid):
        #生成四位随机字符
        from captcha.image import ImageCaptcha
        random_num=random.randint(1000,9999)
        random_str = str(random_num)
#生成验证码
        img = ImageCaptcha()
        img_byte = img.generate(random_str)
        #把验证码存入 redis数据库

        r = redis.Redis(host="127.0.0.1")#连接数据
        key = "code:"+uuid
        r.set(key,random_str,ex=300)
        return HttpResponse(img_byte,content_type='ing_ping')


class CheckimgCode(APIView):
    def get(self, request):
        uuid =request.query_params["imageCodeID"]
        code =request.query_params["imageCode"]

        r = redis.Redis(host="127.0.0.1")  # 连接数据
        key = "code:" + uuid

        system_code =r.get(key)
        system_code =str(system_code,encoding="utf-8")
        print(system_code)
        if system_code.upper()!=code.upper():
            return Response({
                "code":400,
                "msg":'验证码错误'
            })

        return  Response({
            "code":200,
             "msg":'验证码通过'
        })


#注册
class Register(APIView):
    def post(self, request):
        # 前端传入 userName, pwd, mobile, agree
        username = request.data.get("userName")
        password = request.data.get("pwd")
        mobile = request.data.get("mobile")
        agree = request.data.get("agree")
        #验证参数
        if not all([username, password, mobile]):
            return Response({"code":204, "msg":"注册信息不完整!"})
        if not agree:
            return Response({"code":204, 'msg':"未同意用户使用协议"})

        # 存入数据库
        User.objects.create_user(username=username, password=password, mobile=mobile)

        # 返回响应
        return Response({"code":200, "msg":"注册成功!"})

# 登录
class LoginView(APIView):
    def post(self,request):
        # 1.获取前端传来的用户名和密码
        username = request.data.get("user")
        password = request.data.get("pwd")
        # 2.对前端传来的用户名和密码进行校验
        try:
            user = User.objects.get(Q(username=username) | Q(mobile=username))
            # user = User.objects.get(username=username)
        except User.DoesNotExist as e:
            return Response({"msg":"此用户不存在,请先注册","code":400})

        correct = check_password(password,user.password)
        # 返回TRUE 说明用户名和密码匹配
        if correct:
            # 生成token,把生成的token返回
            # 传入第二部分的用户信息
            payload = jwt_payload_handler(user)
            # 根据第二部分生成token
            token = jwt_encode_handler(payload)
            # 把token 写入cookie,便于退出
            # 思考: cookie 是在响应中生成的还是在请求中生成的
            resp = Response({"msg":"登录成功","code":200,'user':{"userName":user.username}})
            # 设置cookie中
            resp.set_cookie('token',token)
            return Response({"msg":"登录成功","code":200,'user':{"userName":user.username}})
        else:
            return Response({"msg":"用户名密码错误","code":400})


class Logout(APIView):
    """退出登录"""
    def post(self, request):

        print(request)
        # 删除cookie
        token = request.COOKIES.get('token')
        if token:
            del token
        return Response({'msg':"退出成功!", "code": 200})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值