RESTful-rest_framework認證組件、許可權組件、頻率組件-第五篇

來源:互聯網
上載者:User

標籤:null   choice   認證通過   models   地址   rto   div   int   xxx   

 

認證組件格式:

1 寫一個認證類        from rest_framework.authentication import BaseAuthentication        class MyAuth(BaseAuthentication):            def authenticate(self,request):        #         request  是封裝後的                token = request.query_params.get(‘token‘)                ret = models.UserToken.objects.filter(token=token).first()                if ret:        #             認證通過                    return                else:                    raise AuthenticationFailed(‘認證失敗‘)            #可以不寫了            def authenticate_header(self,ss):                pass    2 局部使用        authentication_classes=[MyAuth,MyAuth2]    3 全域使用        尋找順序:自訂的APIView裡找---》項目settings裡找---》內建預設的        REST_FRAMEWORK={            ‘DEFAULT_AUTHENTICATION_CLASSES‘:[‘utils.common.MyAuth‘,]        }

 

許可權組件格式:

1 寫一個類        class MyPermission():            def has_permission(self,request,view):                token=request.query_params.get(‘token‘)                ret=models.UserToken.objects.filter(token=token).first()                if ret.user.type==2:                # 超級使用者可以訪問                    return True                else:                    return False    2 局部使用:        permission_classes=[MyPermission,]    3 全域使用:            REST_FRAMEWORK={            ‘DEFAULT_PERMISSION_CLASSES‘:[‘utils.common.MyPermission‘,]        }

 

頻率組件格式:

1 寫一個類:        from rest_framework.throttling import SimpleRateThrottle        class VisitThrottle(SimpleRateThrottle):            scope = ‘xxx‘            def get_cache_key(self, request, view):                return self.get_ident(request)    2 在setting裡配置:            ‘DEFAULT_THROTTLE_RATES‘:{                ‘xxx‘:‘5/h‘,            }    3 局部使用        throttle_classes=[VisitThrottle,]    4 全域使用        REST_FRAMEWORK={            ‘DEFAULT_THROTTLE_CLASSES‘:[‘utils.common.MyPermission‘,]        }

 

執行個體

執行個體簡介:

只有認證通過的使用者才能訪問指定的url地址,比如:查詢課程資訊,需要登入之後才能查看,沒有登入,就不能查看,這時候需要用到認證組件

 

1.mode層

class UserInfo(models.Model):    name=models.CharField(max_length=32)    pwd=models.CharField(max_length=32)    ss=((1,‘超級使用者‘),(2,‘普通使用者‘),(3,‘二逼使用者‘))    type=models.IntegerField(choices=ss,null=True)class UserToken(models.Model):    user=models.OneToOneField(to=‘UserInfo‘)    token=models.CharField(max_length=64)

 

2.views層

from django.shortcuts import render,HttpResponse# Create your views here.import jsonfrom rest_framework.views import APIViewfrom app01 import modelsfrom utils.common import *from rest_framework.response import Response#登入類class Login(APIView):    def post(self,request,*args,**kwargs):        #執行個體化響應狀態函數(添加登入成功後的狀態資訊)        response=MyResponse()        #判斷使用者名稱、密碼是否正確        name=request.data.get(‘name‘)        pwd=request.data.get(‘pwd‘)        user=models.UserInfo.objects.filter(name=name,pwd=pwd).first()        #如果登入成功產生一個隨機字串        if user:            #產生一個隨機字串            token=get_token(name)            #token表裡面的資訊,如果不存在,會建立,如果存在會更新token值(因為進行了隨機時間加鹽),使用的是update_or_create            ret=models.UserToken.objects.update_or_create(user=user,defaults={‘token‘:token})            # ret=models.UserInfo.objects.update_or_create(id=1,defaults={‘token‘:token}) 不是只能寫user或者可以寫id            response.status=100            response.msg=‘登入成功‘            response.token=token            print(response.get_dic())        else:            response.msg="使用者名稱密碼錯誤"            # response.data=‘ddd‘  最後response.get_dic(),都可以把這些資訊返回        #裡面需要傳入個字典        return Response(response.get_dic())#查看課程類class Course(APIView):    #局部登入認證    authentication_classes = [MyAuth,]    #局部許可權認證    permission_classes = [Mypermission,]    #局部頻率認證    throttle_classes = [VisitThrottle,]    def get(self,request):        print(request.user)        print(request.auth)        return HttpResponse(json.dumps({‘name‘:‘python‘}))

 

 

 

2.建立認證類

from rest_framework.exceptions import APIException,AuthenticationFailedclass MyAuth(BaseAuthentication):    def authenticate(self, request):        #拿到的是隨機token的值        token = request.query_params.get(‘token‘)        ret = models.UserToken.objects.filter(token=token).first()        if ret:            #認證通過            return ret.user,ret        else:            #認證失敗            raise AuthenticationFailed(‘認證失敗‘)

 

RESTful-rest_framework認證組件、許可權組件、頻率組件-第五篇

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.