定义个一个认证类

from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication class Authentication(BaseAuthentication):
def authenticate(self,request):
token=request._request.GET.get("token")
token_obj=UserToken.objects.filter(token=token).first()
if not token_obj:
raise exceptions.AuthenticationFailed("验证失败!")
return (token_obj.user,token_obj)

view配置登录后,访问其他url进行认证:

登录:
def get_random_str(user):
import hashlib,time
ctime=str(time.time()) md5=hashlib.md5(bytes(user,encoding="utf8"))
md5.update(bytes(ctime,encoding="utf8")) return md5.hexdigest() from app01.service.auth import * from django.http import JsonResponse
class LoginViewSet(APIView):
authentication_classes = [Authentication,]
def post(self,request,*args,**kwargs):
res={"code":1000,"msg":None}
try:
user=request._request.POST.get("user")
pwd=request._request.POST.get("pwd")
user_obj=UserInfo.objects.filter(user=user,pwd=pwd).first()
print(user,pwd,user_obj)
if not user_obj:
res["code"]=1001
res["msg"]="用户名或者密码错误"
else:
token=get_random_str(user)
UserToken.objects.update_or_create(user=user_obj,defaults={"token":token})
res["token"]=token except Exception as e:
res["code"]=1002
res["msg"]=e return JsonResponse(res,json_dumps_params={"ensure_ascii":False}) 认证:
class BookView(APIView):
    authentication_classes = [Authentication,] # [Authentication(),] 这写入认证累名字即可
    # permission_classes = []
    # throttle_classes = []
        def get(self,request):
        print("request.user",request.user)
        print("request.auth",request.auth)
        print("_request.body",request._request.body)
        print("_request.GET",request._request.GET)
        book_list=Book.objects.all()

以上是局部配置认证

全局配置:

settings.py配置如下:

REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",] #这个代表认证类的位置
}

权限:

class SVIPPermission(object):
message="只有超级用户才能访问"
def has_permission(self,request,view):
username=request.user
user_type=User.objects.filter(name=username).first().user_type if user_type==3: return True # 通过权限认证
else:
return False #不通过会获取上面message 这是全局配置:
setting 配置:
REST_FRAMEWORK = {
 "DEFAULT_PERMISSION_CLASSES": ["app01.utils.SVIPPermission",],
} 局部配置:
class BookView(APIView):
    #authentication_classes = [Authentication,] # [Authentication(),] 这写入认证累名字即可
    # permission_classes = [SVIPPermission] 这些写入局部配合的权限
    # throttle_classes = []
        def get(self,request):
        print("request.user",request.user)
        print("request.auth",request.auth)
        print("_request.body",request._request.body)
        print("_request.GET",request._request.GET)
        book_list=Book.objects.all()

rest_famework 认证与权限组件的更多相关文章

  1. rest-framework组件 之 认证与权限组件

    浏览目录 认证组件 权限组件 频率组件 认证与权限组件 认证组件 局部视图认证 在app01.service.auth.py: class Authentication(BaseAuthenticat ...

  2. DRF(4) - 认证、权限组件

    一.引入 通过前面三节课的学习,我们已经详细了解了DRF提供的几个重要的工具,DRF充分利用了面向对象编程的思想,对Django的View类进行了继承,并封装了其as_view方法和dispatch方 ...

  3. rest-framework认证、权限组件

    认证组件: models class User(models.Model): username = models.CharField(max_length=32) password = models. ...

  4. DRF之版本控制、认证和权限组件

    一.版本控制组件 1.为什么要使用版本控制 首先我们开发项目是有多个版本的当我们项目越来越更新,版本就越来越多,我们不可能新的版本出了,以前旧的版本就不进行维护了像bootstrap有2.3.4版本的 ...

  5. Restful 4 -- 认证组件、权限组件、频率组件、url注册器、响应器、分页器

    一.认证组件.权限组件.频率组件总结:  只有认证通过的用户才能访问指定的url地址,比如:查询课程信息,需要登录之后才能查看,没有登录,就不能查看,这时候需要用到认证组件 1.认证组件格式 写一个认 ...

  6. RESTful-rest_framework认证组件、权限组件、频率组件-第五篇

    认证组件.权限组件.频率组件总结:  认证组件格式: 1 写一个认证类 from rest_framework.authentication import BaseAuthentication cla ...

  7. rest_framework组件之认证,权限,访问频率

    共用的models from django.db import models # Create your models here. class User(models.Model): username ...

  8. DjangoRestFramework学习三之认证组件、权限组件、频率组件、url注册器、响应器、分页组件

    DjangoRestFramework学习三之认证组件.权限组件.频率组件.url注册器.响应器.分页组件   本节目录 一 认证组件 二 权限组件 三 频率组件 四 URL注册器 五 响应器 六 分 ...

  9. Django高级篇三。restful的解析器,认证组件,权限组件

    一.rest=framework之解析器 1)解析器作用. 根据提交的数据.只解析某些特定的数据.非法数据不接收,为了系统安全问题 比如解析的数据格式有 有application/json,x-www ...

随机推荐

  1. Python 汉诺塔

    在汉诺塔游戏中,有三个分别命名为A.B.C得塔座,几个大小各不相同,从小到大一次编号得圆盘,每个原盘中间有一个小孔.最初,所有得圆盘都在A塔座上,其中最大得圆盘在最下面,然后是第二大,以此类推. 游戏 ...

  2. Nginx配置之负载均衡、限流、缓存、黑名单和灰度发布

    一.Nginx安装(基于CentOS 6.5) 1.yum命令安装 yum install nginx –y(若不能安装,执行命令yum install epel-release) 2. 启动.停止和 ...

  3. MySQL出现too many connections(1040)错误解决方法

    https://www.cnblogs.com/2881064178dinfeng/p/6938112.html 其实MySQL默认的最大连接数为100,可能在大访问量的时候造成了连接不上数据库.解决 ...

  4. Scaffold(Material库中提供的页面脚手架)知识点

    Scaffold 包含:appBar.body.floatingActionButton

  5. python selenium-webdriver 处理JS弹出对话框(六)

    在实际系统中,在完成某些操作时会弹出对话框来提示,主要分为"警告消息框","确认消息框","提示消息对话"三种类型的对话框. 1.警告消息框 ...

  6. 获取邮箱使用情况、以及最后一次logon时间

    # 每天收发邮件数 # https://gallery.technet.microsoft.com/scriptcenter/Count-sent-and-recceived-f9c66cf7 # 获 ...

  7. ORACLE数据库自动备份压缩的批处理脚本 rar 7z

    使用7z的版本: @echo offset filename="d:\backup\dbname_%date:~0,10%"set zipfile="d:\backup\ ...

  8. locate中使用variant

    利用locate构造多字段查询,采用variant很方便,简介如下, //构造查询多字段,例如'编号;姓名'形式 aLookField :=  FieldByName ('关键字1').AsStrin ...

  9. windows下 go安装qt绑定

    1.下载安装QT 离线版QT地址:  https://download.qt.io/official_releases/qt/5.11/5.11.1/qt-opensource-windows-x86 ...

  10. Ubuntu14.04安装 ROS 安装步骤和问题总结

    参考: 1.http://wiki.ros.org/indigo/Installation/Ubuntu 2.安装出现依赖库问题: https://answers.ros.org/question/3 ...