rest_framework框架实现之(认证)
一认证
我们可以想想,我们要访问一个页面,需不需要对其进行认证,希望进入页面的时候看到哪些内容,一般是根据用户的不同而不同
首先,我们先设计一个表,如何知道对方通过了验证,我们可以考虑给其加一个token,并且每个人都有不同的权限(大小)
#models.py
from django.db import models class UserInfo(models.Model):
user_type_choices=(
(1,'普通用户'),
(2,'VIP'),
(3,"SVIP")
)
user_type=models.IntegerField(choices=user_type_choices)
username=models.CharField(max_length=32,unique=True)
password=models.CharField(max_length=32) class UserToken(models.Model):
user=models.OneToOneField(to='UserInfo') #默认就是UserInfo表的id
token=models.CharField(max_length=64)
其次,需要设计token,token一般是一长串字符串,我们可以使用md5对其进行转化
#views.py
def md5(user):
import hashlib,time
ctime=str(time.time())
m=hashlib.md5(bytes(user,encoding='utf-8')) #使用bytes方法直接让str变成bytes
m.update(bytes(ctime,encoding='utf-8'))
return m.hexdigest()
设计验证方法
#views.py
from rest_framework.views import exceptions
from api import models
from rest_framework.authentication import BaseAuthentication
#BaseAuthentication类强制要求重写 authenticate函数,要不然抛出异常 .authenticate() must be overridden
class Auth_yanzheng(BaseAuthentication):
def authenticate(self, request):
token = request._request.GET.get('token')
token_obj = models.UserToken.objects.filter(token=token).first()
if not token_obj:
raise exceptions.AuthenticationFailed('用户认证失败')
# 在rest framework内部将两个字段赋值给request,以供后续操作使用
return (token_obj.user, token_obj) #返回元组 def authenticate_header(self, request): #这个要写要不然报错
pass
token从哪里获得?当然是用户登录的时候
#views.py
from rest_framework.views import APIView
from django.http import JsonResponse
class AuthView(APIView): #根据用户登录,找出token,有就更新,没有就新建
def post(self,request,*args,**kwargs):
ret={'code':1000,'msg':None}
try:
user=request._request.POST.get('username')
pwd=request._request.POST.get('password')
obj=models.UserInfo.objects.filter(username=user,password=pwd).first() if not obj:
ret['code']=1001
ret['msg']='用户名或密码错误'
token=md5(user)
models.UserToken.objects.update_or_create(user=obj,defaults={'token':token}) #注意update_or_create方法
ret['token']=token
except Exception as e:
print(e)
ret['code']=1002
ret['msg']='请求异常' return JsonResponse(ret)
接着我们设计一下url
url(r'^api/v1/auth/$',views.AuthView.as_view()),
下面通过postman来实现这一过程,能再数据库里面找到用户信息,则给用户加上一个token

下面,我们来设计另外一个函数,用上我们的认证
#urls.py
url(r'^api/v1/auth/$',views.AuthView.as_view()),
url(r'^api/v1/order/$',views.OrderView.as_view()),
#views.py
ORDER_DICT={
1:{
'name':"hehe",
'age':18,
'gender':'男',
'content':"..."
},
2: {
'name': "go",
'age': 19,
'gender': '男',
'content': "..."
}
}
class OrderView(APIView):
authentication_classes = [Auth_yanzheng]
def get(self,request,*args,**kwargs):
# token=request._request.GET.get('token')
# if not token:
# return HttpResponse('用户未登录') ret={'code':1000,'msg':None,'data':None}
try:
ret['data']=ORDER_DICT #ORDER_DICT是我们给成功认证的用户看的东西
except Exception as e:
pass
return JsonResponse(ret)

总结流程:(单一考虑认证)
首先,经过urls,urls里面执行的是 as_view方法,找as_view方法,我们没写,---》找到父类APIview,APIview继承了view,view里面的as_view方法返回的是dispatch APIview里面的dispatch方法,执行initialize_request函数,它对request进行封装 authenticators=self.get_authenticators(), 函数get_authenticators里面,遍历authentication_classes ---》return [auth() for auth in self.authentication_classes] 接着再全局变量里面找 authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES,没有就找到局部 回到APIview执行initial函数--》执行 self.perform_authentication(request),函数perform_authentication返回 request.user request来自哪里呢,回到封装request的地方,发现request是一个类,找到它的user方法,里面执行 self._authenticate(),_authenticate里面循环类的对象,执行对象的authenticate方法
authenticate就是我们自己写的方法
下面看_authenticate
def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance
in turn.
"""
for authenticator in self.authenticators:
try:
user_auth_tuple = authenticator.authenticate(self) #接收我们给的值
except exceptions.APIException:
self._not_authenticated()
raise if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple #分别赋值给user,auth
return self._not_authenticated()
def _not_authenticated(self):
"""
Set authenticator, user & authtoken representing an unauthenticated request. Defaults are None, AnonymousUser & None.
"""
self._authenticator = None if api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER() #如果经过了,什么用户都没有的情况下,返回默认值 AnonymousUser
else:
self.user = None if api_settings.UNAUTHENTICATED_TOKEN:
self.auth = api_settings.UNAUTHENTICATED_TOKEN()
else:
self.auth = None
rest_framework框架实现之(认证)的更多相关文章
- rest_framework框架之认证功能的使用和源码实现流程分析
rest_framework框架之认证的使用和源码实现流程分析 一.认证功能的源码流程 创建视图函数 Note 创建视图函数后,前端发起请求,url分配路由,执行视图类,视图类中执行对应方法必须经过d ...
- rest_framework框架
rest_framework框架的认识 它是基于Django的,帮助我们快速开发符合RESTful规范的接口框架. 一 路由 可以通过路由as_view()传参 根据请求方式的不同执行对应不同的方法 ...
- rest_framework框架下的Django声明和生命周期
rest_framework框架下的Django声明和生命周期 Django声明周期(request) 客户端发起请求 请求经过wsgi wsgi: 是一个协议----web服务网关接口,即在web服 ...
- SpringMVC整合Shiro,Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能
SpringMVC整合Shiro,Shiro是一个强大易用的Java安全框架,提供了认证.授权.加密和会话管理等功能. 第一步:配置web.xml <!-- 配置Shiro过滤器,先让Shiro ...
- django rest_framework 实现用户登录认证
django rest_framework 实现用户登录认证 1.安装 pip install djangorestframework 2.创建项目及应用 创建过程略 目录结构如图 3.设置setti ...
- rest_framework框架的认证、权限
REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.TokenAuth", ] ...
- rest_framework框架的认识
它是基于Django的,帮助我们快速开发符合RESTful规范的接口框架. 一 路由 可以通过路由as_view()传参 根据请求方式的不同执行对应不同的方法 在routers模块下 封装了很多关于 ...
- django rest_framework 框架的使用
django 的中间件 csrf Require a present and correct csrfmiddlewaretoken for POST requests that have a CSR ...
- Django之REST_framework 框架基本组件使用
快速实例 快速实例: 点击查看官方文档 阅读推荐:点击查看 序列化 创建一个序列化类 简单使用 开发我们的Web API的第一件事是为我们的Web API提供一种将代码片段实例序列化和反序列化为诸如j ...
随机推荐
- zTree节点排序、jsTree节点排序
项目中遇到了这个问题,网上也没找到比较清晰的答案,索性提供一个方案吧. 原理:将整个树形插件的数据源进行排序,插件在构造UI时,自然也是按照顺序来排列的,目前这种思路适用于 zTree 和 jsTre ...
- 升级ceph
参考文档 https://blog.51cto.com/jerrymin/2140258 https://www.virtualtothecore.com/en/upgrade-ceph-cluste ...
- bzoj 2015
http://www.lydsy.com/JudgeOnline/problem.php?id=2015 裸最短路(' ' ) 不过我最初以为是mst (' ' ) #include & ...
- 耗时十个月的德国APS,教会我的学习方法
考过了准备了10个月的Aps ,想送给关注我的8175个粉丝,一份礼物,感谢你们看的起我,对我的支持和关注. 这份礼物,我就大言不惭的称之为:达令的学习方法. 我的考试经历:高考两次,中戏艺考三试,导 ...
- linux c开发项目过程总结
软件工程有瀑布模型,迭代模型等. 使用linux c语言来开发项目,当然也是遵循这样的思想,先要问题定义-->需求分析--->原型设计---->编码及单元测试--->集成测试及 ...
- MySQL 下载,安装,配置windows 服务
本次使用的是压缩包的方式是可以纯手动自己折腾各种配置... ok,闲话少叙,我们准备发车... 一.先要去mysql官网去下载压缩包咯 ①下载地址:https://dev.mysql.com/down ...
- 创建线程方法&守护线程
创建线程方法1. class mythread extends Thread{ 重写run方法 } mythread m=new mythread () 启动:m.start() 创建线程方法2. c ...
- #include和前置声明(forward declaration)
#include和前置声明(forward declaration) 1. 当不需要调用类的实现时,包括constructor,copy constructor,assignment opera ...
- 力扣算法题—149Max Points on a line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. ...
- SSO 实现博客系统的单点登录
https://blog.csdn.net/qq1350048638/article/details/78933375 https://blog.csdn.net/yejingtao703/artic ...