rest-framework组件 之 认证与权限组件
浏览目录
认证与权限组件
认证组件
局部视图认证
在app01.service.auth.py:
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)
views.py:
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})
全局视图认证
settings.py配置如下:
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",]
}
权限组件
局部视图权限
在app01.service.permissions.py中:
from rest_framework.permissions import BasePermission
class SVIPPermission(BasePermission):
message="SVIP才能访问!"
def has_permission(self, request, view):
if request.user.user_type==3:
return True
return False
views.py
from app01.service.permissions import * class BookViewSet(generics.ListCreateAPIView):
permission_classes = [SVIPPermission,]
queryset = Book.objects.all()
serializer_class = BookSerializers
全局视图权限
settings.py配置如下:
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
"DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]
}
throttle(访问频率)组件
局部视图throttle
在app01.service.throttles.py中:
from rest_framework.throttling import BaseThrottle VISIT_RECORD={}
class VisitThrottle(BaseThrottle): def __init__(self):
self.history=None def allow_request(self,request,view):
remote_addr = request.META.get('REMOTE_ADDR')
print(remote_addr)
import time
ctime=time.time() if remote_addr not in VISIT_RECORD:
VISIT_RECORD[remote_addr]=[ctime,]
return True history=VISIT_RECORD.get(remote_addr)
self.history=history while history and history[-1]<ctime-60:
history.pop() if len(history)<3:
history.insert(0,ctime)
return True
else:
return False def wait(self):
import time
ctime=time.time()
return 60-(ctime-self.history[-1])
在views.py中:
from app01.service.throttles import * class BookViewSet(generics.ListCreateAPIView):
throttle_classes = [VisitThrottle,]
queryset = Book.objects.all()
serializer_class = BookSerializers
全局视图throttle
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
"DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",],
"DEFAULT_THROTTLE_CLASSES":["app01.service.throttles.VisitThrottle",]
}
内置throttle类
在app01.service.throttles.py修改为:
class VisitThrottle(SimpleRateThrottle): scope="visit_rate"
def get_cache_key(self, request, view): return self.get_ident(request)
settings.py设置:
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
"DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",],
"DEFAULT_THROTTLE_CLASSES":["app01.service.throttles.VisitThrottle",],
"DEFAULT_THROTTLE_RATES":{
"visit_rate":"5/m",
}
}
rest-framework组件 之 认证与权限组件的更多相关文章
- rest_framework组件之认证,权限,访问频率
共用的models from django.db import models # Create your models here. class User(models.Model): username ...
- Django REST framework 自定义(认证、权限、访问频率)组件
本篇随笔在 "Django REST framework 初识" 基础上扩展 一.认证组件 # models.py class Account(models.Model): &qu ...
- DRF之版本控制、认证和权限组件
一.版本控制组件 1.为什么要使用版本控制 首先我们开发项目是有多个版本的当我们项目越来越更新,版本就越来越多,我们不可能新的版本出了,以前旧的版本就不进行维护了像bootstrap有2.3.4版本的 ...
- DRF(4) - 认证、权限组件
一.引入 通过前面三节课的学习,我们已经详细了解了DRF提供的几个重要的工具,DRF充分利用了面向对象编程的思想,对Django的View类进行了继承,并封装了其as_view方法和dispatch方 ...
- rest-framework认证、权限组件
认证组件: models class User(models.Model): username = models.CharField(max_length=32) password = models. ...
- drf之组件(认证、权限、排序、过滤、分页等)和xadmin、coreapi
认证Authentication 可以在配置文件中配置全局默认的认证方案 REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_fr ...
- Django REST framework基础:认证、权限、限制
认证.权限和限制 身份验证是将传入请求与一组标识凭据(例如请求来自的用户或其签名的令牌)相关联的机制.然后 权限 和 限制 组件决定是否拒绝这个请求. 简单来说就是: 认证确定了你是谁 权限确定你能不 ...
- Django-CRM项目学习(七)-权限组件的设置以及权限组件的应用
开始今日份整理 1.利用自定制标签,增加展示权限,权限分级设定 1.1 在权限组件中创建自定义标签 使用自定义标签的目的,使各个数据进行分离 1.2 导入自定义标签包 自定义标签复习(自定义标签有三种 ...
- day 71 crm(8) 权限组件的设置,以及权限组件的应用
---恢复内容开始--- 前情提要: strak 组件是增删改查组件 , 生活中,需求权限组件, 不足: 1,前后端不分离, 2, 空url也会刷新界面,造成资源浪费 3,如果角色忘记设置权 ...
随机推荐
- Phong光照模型的Shader实现
计算反射向量 Phong用到的是反射向量,计算反射向量的公式是 R = 2*N(dot(N, L)) - L 这个公式是根据向量的投影公式以及平行四边形法则推导出来的 详细步骤请看这篇文章,讲的非常好 ...
- Python collections系列之有序字典
有序字典(orderedDict ) orderdDict是对字典类型的补充,他记住了字典元素添加的顺序 1.创建一个有序字典 import collections dic = collections ...
- Machine Learning的Python环境设置
Machine Learning目前经常使用的语言有Python.R和MATLAB.如果采用Python,需要安装大量的数学相关和Machine Learning的包.一般安装Anaconda,可以把 ...
- Admin.Admin/Login --- 后台项目中的管理员及登录模块
管理员模块: using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sy ...
- rsync mac->windows openssh
rsync -azvP --progress -e "ssh -p 6666" /Users/codar/360\344\272\221\347\233\230/ghld/ rsy ...
- ASP.NET 连接MySql数据库
ASP.NET Mysql操作类 以下连接MySql数据库以VS2010为例,对于其他的编辑器也差不多 1. 我们需要在Mysql官网下载一个组件http://dev.mysql.com/downlo ...
- NSFileManager和NSFileHandle使用
一.NSFileManager: 1.1.获取NSFileManager NSFileManager *manager = [NSFileManager defaultManager]; NS ...
- Shell编程进阶 1.3data命令
date命令是显示日期时间的命令 date 2016年 01月 01日 星期五 15:05:01 CST 修改时间的选项是 -s date -s "2016-01-01 12:56:10&q ...
- DAY14-前端之Bootstrap框架
Bootstrap介绍 Bootstrap是Twitter开源的基于HTML.CSS.JavaScript的前端框架. 它是为实现快速开发Web应用程序而设计的一套前端工具包. 它支持响应式布局,并且 ...
- 解决实现OnPageChangeListener()接口的方法参数出现arg0,arg1的现象
在安卓开发中,我们经常用到ViewPager,那么既然用到ViewPager,一般都需要去实现OnPageChangeListener()接口的三个方法. 但是有时候实现的三个方法的参数都变成agr0 ...