Django rest framework (2) ---- permission

Source: Internet
Author: User
1. Add Permissions

(1) create a premission. py file in the API/utils folder. The Code is as follows:

  • Message is the prompt message when there is no permission
#! /Usr/bin/ENV Python # Coding: utf-8from rest_framework.permissions import basepermissionclass svippermission (basepermission): Message = "must be svip to access, your permission is too low, roll" def has_permission (self, request, view): # request. user indicates to obtain the object if request of the userinfo class. user. user_type! = 3: Return false return trueclass mypermission (basepermission): Message = "no permission to view me, roll" def has_permission (self, request, view): If request. user. user_type = 3: Return false return true

  

(2) settings. py global configuration permission

REST_FRAMEWORK = {    ‘DEFAULT_AUTHENTICATION_CLASSES‘: [‘API.utils.auth.Authentication‘,],    ‘DEFAULT_PERMISSION_CLASSES‘: [‘API.utils.permission.SVIPPermission‘],}

  

(3) add permissions to views. py

  • By default, all services require the svip permission to access
  • The orderview class does not contain the svippremission that indicates the global configuration.
  • Userinfoview class, because it can be accessed by common users and VIP users without the use of global resources, if you want to use it locally, write your own permission class.
  • Permission_classes = [mypremission,] # permission usage method
#! /Usr/bin/ENV Python # Coding: utf-8from Django. shortcuts import render, httpresponsefrom Django. HTTP import jsonresponsefrom rest_framework.views import apiviewfrom API import modelsfrom rest_framework.request import requestfrom rest_framework import exceptionsfrom rest_framework.authentication import basicauthenticationfrom API. utils. permission import svippermission, mypermissionimport hashlibimport timedef MD5 (User): ctime = STR (time. time () M = hashlib. MD5 (User) M. update (ctime) return M. hexdigest () Class authview (apiview): authentication_classes = [] permission_classes = [] def post (self, request, * ARGs, ** kwargs): ret = {'code ': 1000, 'msg ': None} Try: User = request. post. get ('username') Pwd = request. post. get ('Password') print (user, PWD) OBJ = models. userinfo. objects. filter (username = user, password = PWD ). first () print ('=================% s' % (OBJ) if not OBJ: RET ['code'] = 1001 RET ['msg '] = 'username or password error' # Create a token = MD5 (User) for the user # update the token if it exists, create models if it does not exist. usertoken. objects. update_or_create (user = OBJ, defaults = {'Token': token}) RET ['Token'] = token cannot exception as E: RET ['code'] = 1002 RET ['msg '] = 'request exception' # user = request. _ request. post. get ('username') # Pwd = request. _ request. post. get ('Password') # print (user, PWD) # OBJ = models. userinfo. objects. filter (username = user, password = PWD ). first () # print ('===================% s' % (OBJ) # if not OBJ: # RET ['code'] = 1001 # RET ['msg '] = 'user name or password error' # Create a token for the user # token = MD5 (User) # update if it exists and create if it does not exist # models. usertoken. objects. update_or_create (user = OBJ, defaults = {'Token': token}) # RET ['Token'] = token return jsonresponse (RET) order_dict = {1: {'name ': 'apple', 'price': 15,}, 2: {'name': 'Dog', 'price': 100 }}# class authentication (apiview ): # "# authentication class #" "# 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 ('user authentication failed') # the two fields are assigned to the request in the rest framework for future use # Return (token_obj.user, token_obj) # def authenticate_header (self, reqeust): # passclass orderview (apiview): "order-related businesses" "# authentication_classes = [] # Add authentication def get (self, request, * ARGs, ** kwargs): Print (request. user) print (request. auth) # print (request. _ dict _) ret = {'code': 1000, 'msg ': None, 'data': None} try: RET ['data'] = order_dict failed t exception as E: Pass return jsonresponse (RET) Class userinfoview (apiview): permission_classes = [mypermission] def get (self, request, * ARGs, ** kwargs): Print (request. user) return httpresponse ('user information ')

  

URLs. py

from django.conf.urls import urlfrom django.contrib import adminfrom API import viewsurlpatterns = [    # url(r‘^admin/‘, admin.site.urls),    url(r‘api/v1/auth‘, views.AuthView.as_view()),    url(r‘api/v1/order‘, views.OrderView.as_view()),    url(r‘api/v1/info‘, views.UserInfoView.as_view()),]

  

API/utils/auth. py

#! /Usr/bin/ENV Python # Coding: utf-8from rest_framework import exceptionsfrom API import modelsfrom rest_framework.authentication import basicauthenticationclass authentication (basicauthentication): 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 ('authentication failed') Return (token_obj.user, token_obj) def authenticate_header (self, request): Pass

  

(4) test

Get my token first

 

First, let's see who is there.

 

Let's take a look at the Permission Logic. If user_type = 3, there is no permission, and the message is defined, so I can roll it out.

#! /Usr/bin/ENV Python # Coding: utf-8from rest_framework.permissions import basepermissionclass svippermission (basepermission): Message = "must be svip to access, your permission is too low, roll" def has_permission (self, request, view): # request. user indicates to obtain the object if request of the userinfo class. user. user_type! = 3: Return false return trueclass mypermission (basepermission): Message = "no permission to view me, roll" def has_permission (self, request, view): If request. user. user_type = 3: Return false return true

  

Let's look at the order information.

 

2. Permission source code process

(1) Dispatch

Def dispatch (self, request, * ARGs, ** kwargs ):"""'. dispatch () 'is pretty much the same as Django's regular dispatch, but with extra hooks for startup, finalize, and exception handling. "self. ARGs = ARGs self. kwargs = kwargs # process the original request and enrich some functions # request (# request, # parsers = self. get_parsers (), # authenticators = self. get_authenticators (), # negotiator = self. get_content_negotiator (), # parser_c Ontext = parser_context #) # request (original request, [basicauthentications object,]) # obtain native request, request. _ Request # Get the authentication Class Object, request. authticators #1. encapsulate request = self. initialize_request (request, * ARGs, ** kwargs) self. request = request self. headers = self. default_response_headers # deprecate? Try: #2. authenticate self. initial (request, * ARGs, ** kwargs) # Get the appropriate handler method if request. method. lower () in self. http_method_names: Handler = getattr (self, request. method. lower (), self. http_method_not_allowed) else: Handler = self. http_method_not_allowed response = handler (request, * ARGs, ** kwargs) handle T exception as exc: Response = self. handle_exception (EXC) self. response = self. finalize_response (request, response, * ARGs, ** kwargs) return self. response

  

(2) Initial

Def initial (self, request, * ARGs, ** kwargs): "" runs anything that needs to occur prior to calling the method handler. "self. format_kwarg = self. get_format_suffix (** kwargs) # perform content negotiation and store the accepted info on the request neg = self. required m_content_negotiation (request) request. accepted_renderer, request. accepted_media_type = neg # determine the API version, if Versioning is in use. version, scheme = self. determine_version (request, * ARGs, ** kwargs) request. version, request. versioning_scheme = version, scheme # ensure that the incoming request is permitted #4. implement self authentication. optional m_authentication (request) #5. permission judgment self. check_permissions (request) self. check_throttles (request)

  

(3) check_permissions

There is a has_permission in it. This is the permission judgment we write.

Def check_permissions (self, request): "" check if the request shocould be permitted. raises an appropriate exception if the request is not permitted. "# [permission Class Object List] for permission in self. get_permissions (): If not permission. has_permission (request, self): Self. permission_denied (request, message = getattr (permission, 'message', none ))

  

(4) get_permissions

 def get_permissions(self):        """        Instantiates and returns the list of permissions that this view requires.        """        return [permission() for permission in self.permission_classes]

 

 

 

 

The global settings configuration is as follows:

# Global rest_framework = {"default_permission_classes": ['api. utils. Permission. svippremission'],}

  

Three built-in Permissions

Django-rest-framework built-in permission basepermission

By default, there is no restriction on permissions.

class BasePermission(object):    """    A base class from which all permission classes should inherit.    """    def has_permission(self, request, view):        """        Return `True` if permission is granted, `False` otherwise.        """        return True    def has_object_permission(self, request, view, obj):        """        Return `True` if permission is granted, `False` otherwise.        """        return True

  

The permission class we write should inherit basepermission and modify the previously written permission. py file.

# Utils/permission. pyfrom role import basepermissionclass svippremission (basepermission): Message = "must be svip to access" def has_permission (self, request, view): If request. User. user_type! = 3: Return false return trueclass mypremission (basepermission): def has_permission (self, request, view): If request. User. user_type = 3: Return false return true

  

Summary:

(1) Use

  • Permission classes written by yourself: 1. The basepermission class must be inherited; 2. the has_permission method must be implemented.

(2) Return Value

  • True
  • False

(3) Local

  • Permission_classes = [mypremission,]

(4) Global

Rest_framework = {# permission "default_permission_classes": ['api. utils. Permission. svippremission'],}

  

Okay. The permission is still so easy.

 

Django rest framework (2) ---- permission

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.