Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Django-Rest-Framework Rights Management Source Code

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the Django-Rest-Framework rights management source code example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

In django's views, no matter using the rest framework by class or decorator, django_rest_frame needs the cooperation of two things: authentication_classes and permission_classes.

# method 1: decorator from rest_framework.decorators import api_view, authentication_classes, permission_classesfrom rest_framework.authentication import SessionAuthentication, BasicAuthenticationfrom rest_framework.permissions import AllowAnyfrom rest_framework.response import Response@api_view (["GET",]) @ permission_classes ([AllowAny,]) @ authentication_classes ([SessionAuthentication, BasicAuthentication]) def test_example (request): content = {'user': unicode (request.user), # `django.contrib.auth.User` instance. 'auth': unicode (request.auth), # None} return Response (content) #-# method 2: class from rest_framework.authentication import SessionAuthentication BasicAuthenticationfrom rest_framework.permissions import AllowAnyfrom rest_framework.response import Responsefrom rest_framework.views import APIViewclass ExampleView (APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (AllowAny,) def get (self, request, format=None): content = {'user': unicode (request.user), # `django.contrib.auth.User` instance. 'auth': unicode (request.auth), # None} return Response (content)

The default scheme for permission configuration is given above, and there is no difference between write and no write. The rest framework has its own settings file, in which the original default values can be found:

When it comes to rest's settings file, to override the default behavior, especially the permission authentication behavior, we only need to set the settings file in the project

Just specify your own class in:

REST_FRAMEWORK = {... 'DEFAULT_AUTHENTICATION_CLASSES': ('your_authentication_class_path',),...}

In the settings file of rest, when you get the properties, the settings in the project's settings file are loaded first, and if you don't have them in the project, your default settings are loaded:

Initialize the api_settings object

Api_settings = APISettings (None, DEFAULTS, IMPORT_STRINGS)

When you get the property in the APISettings class, you first get the value of the REST_FRAMEWORK object in the project's settings file, and if you don't have it, find your own default value.

@ propertydef user_settings (self): if not hasattr (self,'_ user_settings'): # _ user_ settings defaults to loading the REST_FRAMEWORK object in the project settings file self._user_settings = getattr (settings, 'REST_FRAMEWORK', {}) return self._user_settingsdef _ _ getattr__ (self) Attr): if attr not in self.defaults: raise AttributeError ("Invalid API setting:'% s'"% attr) try: # Check if present in user settings # load user_settings first That is, the settings file of the project. If there is no default val = self.user_ settings [attr] except KeyError: # Fall back to defaults val = self.defaults [attr] # Coerce import strings into classes if attr in self.import_strings: val = perform_import (val, attr) # Cache the result self._cached_attrs.add (attr) setattr (self, attr, val) return val

In settings in rest, you can automatically detect changes to the project settings and reload your own configuration file:

A brief Analysis of the principle of Authority Management

How does the rest framework use authentication_classes and permission_classes and combine them for rights management?

When using class implementation, we will directly or indirectly use APIVIEW in the rest framework, and use the as_view method of this class to build router in urls.py

# views.pyfrom rest_framework.views import APIViewfrom rest_framework.permissions import IsAuthenticatedclass ExampleAPIView (APIView): permission_classes = (IsAuthenticated,). #-- from django.conf.urls import url, includefrom .views import ExampleAPIViewurlpatterns = [url (r'^ example/ (? P [-\ w] +) / examples/?$', ExampleAPIView.as_view ()),]

When we call APIVIEW.as_view (), the class calls the parent class's method with the same name:

The dispatch method is called in the method of the same name of the parent class:

Rest overrides this method, in which requset is initialized on the server side (adding verification information, etc.)

Invoke rights management

The default or your specified permission authentication will be used for verification in the permission management: here, the verification is done and the verification result is stored. After the operation here, the function of authentication_classes is completed. The verification results will be used in the permission_classes specified later!

Def get_authenticators (self): "Instantiates and returns the list of authenticators that this view can use." Return [auth () for auth in self.authentication_classes]

Determine whether there is access to the current interface through the specified permission_classes:

Class IsAuthenticatedOrReadOnly (BasePermission): "The request is authenticated as a user, or is a read-only request." Def has_permission (self, request, view): return (request.method in SAFE_METHODS or request.user and request.user.is_authenticated)

Finally, regardless of whether you use permission_classes to determine whether you can access it or not, the default or your own specified authentication_classes will execute and put the permission result in the request!

Thank you for reading this article carefully. I hope the article "sample Analysis of Django-Rest-Framework Rights Management Source Code" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report