DjangoRestFramework实现用户注册

  1. 创建一个Django应用MyFirstApp,并使用DjangoRestFramework中的路由
    screenshot.png
    screenshot_4.png

  2. 设计数据库模型类models.py

class UUIDTools(object):
    @staticmethod
    def uuid4_hex():
        return uuid.uuid4().hex


class User(models.Model):
    # default指定的是一个类,每次会创建一个新的对象,然后调用相关方法
    id = models.UUIDField(primary_key=True, auto_created=True, default=UUIDTools.uuid4_hex, editable=False)
    username = models.CharField(max_length=32, unique=True)

    password = models.CharField(max_length=256)
    # null=True, blank=True, 表示创建用户时该字段为可选字段
    mobile = models.CharField(max_length=11, blank=True, unique=True)
    email = models.EmailField(max_length=64, blank=True, unique=True)

    def set_password(self, password):
        self.password = encrypt_password(password)

    def verify_password(self, password):
        return self.password == encrypt_password(password)
  1. 第二步中使用md5算法加密用户输入的密码
import hashlib


def encrypt_password(password):
    # 加盐方式,使用md5算法对密码进行加密
    md5 = hashlib.md5()
    sign_str = password + '#@%^&*'
    sign_bytes_utf8 = sign_str.encode(encoding='utf-8')

    md5.update(sign_bytes_utf8)
    encrypted_password = md5.hexdigest()

    return encrypted_password
  1. 设计序列化器serializers.py
# -*-coding:utf-8-*-
from rest_framework import serializers

from FirstApp.models import User


class UserSerializer(serializers.ModelSerializer):
    # style表示前台输入是密文,write_only表示序列化时不会序列化该字段
    password = serializers.CharField(style={'input_type': 'password'}, write_only=True, max_length=256)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'email')

    # 创建用户时更新密码为密文
    def create(self, validated_data):
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

    # 更新用户时更新密码为密文
    def update(self, instance, validated_data):
        user = super().update(instance, validated_data)
        if 'password' in validated_data.keys():
            user.set_password(validated_data['password'])
        user.save()
        return user

    # 重写to_representation方法,自定义响应中的json数据
    def to_representation(self, instance):
        # 返回结果中id字段中间有横线,需要去除
        ret = super().to_representation(instance)
        ret['id'] = ret['id'].replace('-', '')
        return ret
  1. 设计路由urls.py
# -*-coding:utf-8-*-
from rest_framework.routers import DefaultRouter

from FirstApp import views

router = DefaultRouter()
router.register(r'api/users', views.UserViewSet)
  1. 设计视图类views.py
# -*-coding:utf-8-*-
from rest_framework.viewsets import ModelViewSet

from FirstApp.models import User
from FirstApp.serializers import UserSerializer


class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
  1. 用户增删该查效果图

screenshot_1.png
screenshot_6.png
screenshot_3.png
screenshot_5.png
screenshot_2.png
screenshot_7.png

posted @ 2020-04-11 16:20  iread9527  阅读(979)  评论(0编辑  收藏  举报