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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM