DjangoRestFramework实现用户注册
-
创建一个Django应用MyFirstApp,并使用DjangoRestFramework中的路由
-
设计数据库模型类
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)
- 第二步中使用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
- 设计序列化器
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
- 设计路由
urls.py
# -*-coding:utf-8-*-
from rest_framework.routers import DefaultRouter
from FirstApp import views
router = DefaultRouter()
router.register(r'api/users', views.UserViewSet)
- 设计视图类
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
- 用户增删该查效果图
我在想我要不要写一句励志的话......