目录
- 一:导入模块
- 二 :生成token
- 1:定义model,Userinfo和UserToken
- 2:执行数据迁移命令,生成表数据
- 3:用户注册
- 4:根据用户名生成token
- 三:自定义权限类
- 1:自定义权限类
- 2:编写views
- 3:配置url
- 4:测试
- 四:全局配置
一:导入模块
pip install djangorestframeword # 使用pip命令进行djangorestFramework
二 :生成token
1:定义model,Userinfo和UserToken
from django.db import models
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:10/3/2020 下午2:14
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
class Userinfo(models.Model):
USER_TYPE = (
(1, '普通用户'),
(2, 'VIP'),
(3, 'SVIP')
)
user_type = models.IntegerField(choices=USER_TYPE, blank=True, null=True)
userName = models.CharField(max_length=10)
userPwd = models.CharField(max_length=100)
userTelphone = models.CharField(max_length=10)
userAddress = models.CharField(max_length=10)
userAge = models.CharField(max_length=4)
class UserToken(models.Model):
user = models.OneToOneField(Userinfo, on_delete=models.CASCADE)
token = models.CharField(max_length=64)
2:执行数据迁移命令,生成表数据
var foo = 'bar';
python manage.py makemigrations zhylbwg
python manage.py migrate zhylbwg
3:用户注册
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:5/3/2020 下午1:50
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
from django.shortcuts import render,HttpResponse
import pandas as pd
import json
from zhylbwg.models import loginModels
from zhylbwg.views import md5
from zhylbwg.views import requestResult
def register(request):
if request.method == "POST":
registerinformation = request.body
registerinformationData = json.loads(registerinformation)
userName = registerinformationData.get('userName')
userNameDB = loginModels.Userinfo.objects.filter(userName=userName)
if not userNameDB:
return HttpResponse(json.dumps(requestResult.result_json('312', '该用户名已经存在', '')),
content_type="application/json,charset=utf-8")
else:
userPwd = registerinformationData.get('userPwd')
userPwdMd5 = md5.Md5(userPwd)
registerinformationData["userPwd"] = userPwdMd5
loginModels.Userinfo.objects.create(**registerinformationData)
return HttpResponse(json.dumps(requestResult.result_json('201', '注册成功,请登录', '')),
content_type="application/json,charset=utf-8")
else:
return HttpResponse(json.dumps(requestResult.result_json('501', '不是post请求', '')),
content_type="application/json,charset=utf-8")
- 测试注册接口
- 生成md5工具类
# -*- coding: utf-8 -*-
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:5/3/2020 下午1:50
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
import hashlib # 使用hashlib模块进行md5操作
def Md5(str):
md5 = hashlib.md5() # 创建md5对象
# 此处必须声明encode
# 若写法为hl.update(str) 报错为: Unicode-objects must be encoded before hashing
md5.update(str.encode(encoding='utf-8'))
# 把输入的旧密码装换为md5格式
result = md5.hexdigest()
# 返回加密结果
return result
# -*- coding: utf-8 -*-
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:5/3/2020 下午1:50
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
# 定义统一的json返回格式
def result_json(code, msg, data):
# 创建一个空字典
result = {"code": code, "msg": msg, "data": data}
return result
4:根据用户名生成token
# -*- coding: utf-8 -*-
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:10/3/2020 下午2:14
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.views import APIView
from zhylbwg.models.auth import auth_models
from zhylbwg.views import md5
from django.views import View
from zhylbwg.models import loginModels
'''
用户验证,当用户首次登录时随机生成一个token
'''
# CBV 视图模式
class AuthView(APIView):
'''
在配置了全局认证的情况下,可以使用authentication_classes = [] 表示该视图不进行认证
'''
authentication_classes = []
def post(self, request):
ret = {'code': 1000, 'msg': None}
try:
user = request.POST.get('username')
pwd = md5.Md5(request.POST.get('password'))
obj = loginModels.Userinfo.objects.filter(userName=user, userPwd=pwd).first()
if not obj:
ret['code'] = 1001
ret['msg'] = '用户名或密码错误'
# 为用户创建token
token = md5.Md5(user)
print(token)
# 存在就更新,不存在就创建
loginModels.UserToken.objects.update_or_create(user=obj, defaults={'token': token})
ret['token'] = token
except Exception as e:
ret['code'] = 1002
ret['msg'] = '请求异常'
return JsonResponse(ret)
三:自定义权限类
1:自定义权限类
#-*- coding: utf-8 -*-
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:11/3/2020 下午1:40
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
# 超管角色级别访问的信息
from rest_framework.permissions import BasePermission
'''
自定义权限类的使用步骤
(1)使用
自己写的权限类:1.必须继承BasePermission类; 2.必须实现:has_permission方法
(2)返回值
True 有权访问
False 无权访问
(3)局部
permission_classes = [MyPremission,]
(4)全局
REST_FRAMEWORK = {
#权限
"DEFAULT_PERMISSION_CLASSES":['zhylbwg.utils.premission.AdminRolePremission'],
}
'''
class AdminRolePremission(BasePermission):
message = "必须是超级管理员角色才能访问"
def has_permission(self,request,view):
print(request.user.userName)
if request.user.user_type != 1:
return False
return True
# 客服角色级别访问的信息
class DocterRolePremission(BasePermission):
message = "必须是客服角色才能访问" # 这里的message表示如果不通过权限的时候,错误提示信息
def has_permission(self,request,view):
if request.user.user_type == 2 or request.user.user_type==1:
# False表示没有权限,提示message的信息
# True 便是有权限,继续执行
return False # 若user_type 的值恒等于2 ,则表示权限不通过,输出提示message的信息
return True
# 客服角色级别访问的信息
class AdminAndDoctorRolePremission(BasePermission):
message = "必须是超级管理员或者医生角色才能访问"
def has_permission(self,request,view):
print(request.user.userName)
if request.user_type == 3:
return False
return True
2:编写views
#-*- coding: utf-8 -*-
'''===================================
@Project:wisdomShop
@Author:班婕妤
@Date:11/3/2020 下午1:50
@Company:深圳市智慧养老宝科技有限公司
@Motto:心有猛虎,细嗅蔷薇
@Python_Version:3.7.3
@Django_Version:2.1.5
======================================='''
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from rest_framework.views import APIView
from zhylbwg.models import loginModels
from rest_framework.request import Request
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
from zhylbwg.util import premissionSelf
from zhylbwg.util.authenticationSelf import AuthenticationSelf
from zhylbwg.util.premissionSelf import DocterRolePremission
from zhylbwg.views import md5
ORDER_DICT = {
1:{
'name':'apple',
'price':15
},
2:{
'name':'dog',
'price':100
}
}
class DoctorOrderView(APIView):
'''
订单相关业务(只有SVIP用户才能看)
'''
authentication_classes = [AuthenticationSelf,] # 局部认证
permission_classes = [DocterRolePremission,] # 局部权限
def get(self,request,*args,**kwargs):
print(request.user.user_type)
self.dispatch
#request.user
#request.auth
ret = {'code':1000,'msg':None,'data':None}
try:
ret['data'] = ORDER_DICT
except Exception as e:
pass
return JsonResponse(ret)
class AdminAndDoctorOrderView(APIView):
'''
订单相关业务(只有SVIP用户才能看)
'''
def get(self,request,*args,**kwargs):
self.dispatch
#request.user
#request.auth
ret = {'code':1000,'msg':None,'data':None}
try:
ret['data'] = ORDER_DICT
except Exception as e:
pass
return JsonResponse(ret)
class UserInfoView(APIView):
'''
订单相关业务(普通用户和VIP用户可以看)
'''
# permission_classes = [MyPremission,] #不用全局的权限配置的话,这里就要写自己的局部权限
def get(self,request,*args,**kwargs):
print(request.user)
return HttpResponse('用户信息')
3:配置url
# 角色权限控制
path('zhylbwg/per/admin/', AuthView.as_view()), # 生成token
path('zhylbwg/per/doctor/', DoctorOrderView.as_view()), # 医生权限测
path('zhylbwg/per/admin/', CustomerRoleOrderView.as_view()), # 医生权限测
path('zhylbwg/per/adminAndDoctor/', AdminAndDoctorOrderView.as_view()), # 超管和医生权限
4:测试
四:全局配置
1:全局配置
REST_FRAMEWORK = {
# 全局认证类不要放在views下
"DEFAULT_AUTHENTICATION_CLASSES":['zhylbwg.util.authenticationSelf.AuthenticationSelf',],
# 全局权限配置
"DEFAULT_PERMISSION_CLASSES":['zhylbwg.util.premissionSelf.DocterRolePremission',]
}
2:权限过滤