-
創建一個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
- 用戶增刪該查效果圖