Django framework for understanding _03 (DRF certification of components, assemblies permission)

First, the authentication component

Instructions:

① write a certification class, the new file: my_examine.py

# Import need to inherit base class BaseAuthentication 
from rest_framework.authentication Import BaseAuthentication
 from rest_framework.exceptions Import AuthenticationFailed
 from app01 Import Models 

# create an authentication class that inherits BaseAuthentication 
class MyAuth (BaseAuthentication):
     # secured authenticate write a specific authentication method used to define the content 
    def the authenticate (Self, request):
         # write authentication logic code 
        # example, assume the data token from the backend database, the request sent by the front end requires authentication token 
        token = request.GET.get ( ' token ' ) 
        token_objModels.Token.objects.filter = (token = token) .first ()
         IF token_obj:
             # has a value representative of token verification by 
            # may be used to take token_obj.user currently logged in user object 
            
            # here need to return two data 
            return token_obj the .user, token_obj
         the else :
             The raise AuthenticationFailed ( ' unauthorized ' )

Topical: adding authentication in the view class:

from app01.my_examine import MyAuth
# Create your views here.

class Books(APIView):
    # 给Books视图类添加token认证
    authentication_classes = [MyAuth, ]
    def get(self, request):
        response = {'code': 100, 'msg': '查询成功'}
        books = models.Book.objects.all()
        books_ser = BookSer(instance=books, many=True)
        response['data'] = books_ser.data
        return Response(response)

Global Authentication settings to use:

In the configuration in settings.py

REST_FRAMEWORK={
                "DEFAULT_AUTHENTICATION_CLASSES":["app01.my_examine.MyAuth",]
            }

 

Global certification has been set, in view of all the classes will be certified set value, which is obviously not realistic, because some view can not set up authentication, such as register, login

So it is necessary to disable local authentication authentication method:

Add partial view similar positions following authentication codes, partially complete disabling 
authentication_classes = []

 

Summary :( By analyzing the source code)

- If you configure REST_FRAMEWORK in setting.py project, the default setting to start projects to take
             - if not taken, before going to the default configuration file drf take
             - When you configure a view in a class, go to user configuration takes 
            
            summary: 
                first take the view class configuration ---- "---- take the project setting in" default configuration

token Quick description:

 token implementation process: after successful login will be sent along with the data in response to the front-end with the front end save through their own encryption algorithm to calculate user-related and only a string of string (token) on the server side, the next time the user sends a request to access when the token will be sent together with the back-end data servers, back-end server will first be verified on the token (check this place may be the middleware can be in the view), the process of verification by the user is substantially again relevant data encryption algorithm to calculate the user's token strings, now get out of the token count and stored in the front-end user token sent by match, if the agreement on behalf of the user authentication login is successful, of course, you can set this token is a valid time. To some extent eased the pressure on the server.

Interface login token written application:

models.py

# models.py

class User(models.Model):
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    choices = (('1', 'Super_Admin'), ('2', 'General_Admin'), ('3', 'General_User') )
    user_type = models.CharField(max_length=6, choices=choices, default='3')

#User table associated with doing one 
class Token (models.Model): 
    token = models.CharField (= 64-max_length ) 
    the User = models.OneToOneField (to = ' User ' )

 

 

 

views.py

# views.py

from rest_framework.response import Response
from app01.my_examine import MyAuth
# Create your views here.

from uuid import uuid4
from django.core.exceptions import ObjectDoesNotExist
class Login(APIView):
    def post(self, request):
        response = {'code': 100, 'msg': '登录成功'}
        name = request.data.get('name ' ) 
        password = request.data.get ( ' password ' )
         the try :
             # using the get method, a get method can only take the data, or if a plurality of the reach, it will throw exception 
            user = models.User.objects. filter (name = name, password = password) .get ()
             # capture by abnormal try method, described here come if there is no abnormality, get method to get the user object, the user is logged 
            # successful login data needs to be stored token table ( here assume token is stored in the server database) 
            # generate id a sweater using uuid module 
            token = uuid4 ()
             # token, if present in the user database is updated, if not create 
            # use update_or_create method 
            models.Token. objects.update_or_create (user = user, defaults = {' Token ' : token})
             # The token into the dictionary returned 
            Response [ ' token ' ] = token
         # capture a particular abnormality, user if the object does not exist will here take 
        the except of ObjectDoesNotExist AS E: 
            Response [ ' code ' ] = 101 
            Response [ ' MSG ' ] = ' user name or password is incorrect " 
        # capture other abnormal 
        the except exception AS E: 
            Response [ ' code ' ] = 102 
            Response [ ' MSG' ] = ' Unknown error ' 
        # returned data distal 
        return the Response (Response)

 

Add routes:

url(r'^login/', views.Login.as_view()),

 

Second, the authority component

Usage permissions and authentication component is substantially the same components:

Instructions:

① write a privilege class, still in my_examine.py in:

from rest_framework.permissions import BasePermission
# 创建认证类,BasePermission
class MyPermission(BasePermission):
    message = '权限不足,无法查看'
    # 固定写一个has_permission方法用于定义具体权限内容
    def has_permission(self, request, view):
        # #因为权限在认证之后执行的,所有能取到reuqest.user
        if request.user.user_type == '1':
            return True
        else:
            return False

 

局部使用:

-在视图类中写
permission_classes=[MyPermision,]

 

 全局使用:

在settings.py中配置
REST_FRAMEWORK={
    "DEFAULT_PERMISSION_CLASSES":["app01.my_examine.MyPermision",]
}

 

局部禁用:

-在视图类中写
permission_classes = []

 

这里可以设置添加一个代码让返回显示中文提示:

# 在MyPermision类下面添加
message = '权限不足,无法查看'

 

Guess you like

Origin www.cnblogs.com/suguangti/p/11130015.html