本文共 8717 字,大约阅读时间需要 29 分钟。
导入模块
pip install djangorestframeword # 使用pip命令进行djangorestFramework
配置,在setting.py中进行如下配置
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)
// An highlighted blockvar foo = 'bar';
python manage.py makemigrations zhylbwgpython manage.py migrate zhylbwg
# -*- coding: utf-8 -*- '''=================================== @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 # 导入自定义md5加密函数 from zhylbwg.views import requestResult # 导入自定义的统一返回函数 def register(request): # 判断是否为post请求 if request.method == "POST": # 获取请求头数据,请求以json的格式传输 registerinformation = request.body # 将请求头数据转化为json格式 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') # 密码加密操作md5,md5加密功能具体看md5加密代码 userPwdMd5 = md5.Md5(userPwd) # 将加密后的密码赋值给请求头中的密码参数 registerinformationData["userPwd"] = userPwdMd5 # 将json格式数据,类型为dict 存储到数据库中,表明为Userinfo,将注册请求存储到数据库中 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")
// An highlighted block# -*- 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
// An highlighted block# -*- 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
// An highlighted block# -*- 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 renderfrom django.http import JsonResponsefrom rest_framework.views import APIViewfrom zhylbwg.models.auth import auth_modelsfrom zhylbwg.views import md5from django.views import Viewfrom 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)
// An highlighted block#-*- coding: utf-8 -*-'''===================================@Project:wisdomShop@Author:班婕妤@Date:10/3/2020 下午6:09@Company:深圳市智慧养老宝科技有限公司@Motto:心有猛虎,细嗅蔷薇@Python_Version:3.7.3@Django_Version:2.1.5======================================='''from django.db import modelsfrom django.http import JsonResponsefrom rest_framework import exceptionsfrom zhylbwg.models import loginModelsfrom rest_framework.authentication import BaseAuthentication################################################## 自定义认证类路径不能放在 ## views下,可单独建立目录存放 ##################################################''' 自己写认证类方法梳理 (1)创建认证类 继承BaseAuthentication --->> 1.重写authenticate方法; 2.authenticate_header方法直接写pass就可以(这个方法必须写) (2)authenticate()返回值(三种) None ----->>>当前认证不管,等下一个认证来执行 raise exceptions.AuthenticationFailed('用户认证失败') # from rest_framework import exceptions 有返回值元祖形式:(元素1,元素2) #元素1复制给request.user; 元素2复制给request.auth (3)局部使用 authentication_classes = [BaseAuthentication,] (4)全局使用 #设置全局认证 REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES":['API.utils.auth.Authentication',] }'''class AuthenticationSelf(BaseAuthentication): '''认证''' def authenticate(self,request): print("========") print(request) token = request._request.GET.get('token') print(token) token_obj = loginModels.UserToken.objects.filter(token=token).first() print(token_obj) if not token_obj: raise exceptions.AuthenticationFailed('用户认证失败-请申请认证') #在rest framework内部会将这两个字段赋值给request,以供后续操作使用 return (token_obj.user,token_obj) def authenticate_header(self, request): pass
2:模拟一个订单视图
// An highlighted block#-*- coding: utf-8 -*-'''===================================@Project:wisdomShop@Author:班婕妤@Date:10/3/2020 下午6:09@Company:深圳市智慧养老宝科技有限公司@Motto:心有猛虎,细嗅蔷薇@Python_Version:3.7.3@Django_Version:2.1.5======================================='''from django.http import JsonResponsefrom rest_framework.views import APIViewfrom zhylbwg.util.authenticationSelf import AuthenticationSelfORDER_DICT = { 1:{ 'name':'apple', 'price':15 }, 2:{ 'name':'dog', 'price':100 }}class OrderView(APIView): '''订单相关业务''' authentication_classes = [AuthenticationSelf,] #添加局部认证 def get(self,request,*args,**kwargs): ret = { 'code':1000,'msg':None,'data':None} try: ret['data'] = ORDER_DICT except Exception as e: pass return JsonResponse(ret)
// An highlighted block path('zhylbwg/auth/', AuthView.as_view()), # 生成token path('zhylbwg/authe/', OrderView.as_view()), # 订单视图
// An highlighted block# 配置全局认证 REST_FRAMEWORKREST_FRAMEWORK = { # 全局认证类不要放在views下 "DEFAULT_AUTHENTICATION_CLASSES":['zhylbwg.util.authenticationSelf.AuthenticationSelf',]}
// An highlighted blockauthentication_classes = [AuthenticationSelf,] #添加局部认证
// An highlighted block''' 在配置了全局认证的情况下,可以使用authentication_classes = [] 表示该视图不进行认证 ''' authentication_classes = []
转载地址:http://yaqms.baihongyu.com/