当前位置:网站首页>DRF -- authentication, authority, frequency source code analysis, global exception handling, automatic generation of interface documents, RBAC introduction
DRF -- authentication, authority, frequency source code analysis, global exception handling, automatic generation of interface documents, RBAC introduction
2022-07-29 00:47:00 【There is a car on the hill】
List of articles
List of articles
One 、 Authentication source code analysis
All views are based on APIView
class APIView(View):
# Get authentication configuration
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
#
settings = api_settings
then APIView Of as_view Will run dispatch Method
def dispatch(self, request, *args, **kwargs):
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
# Run here initial To handle authentication
self.initial(request, *args, **kwargs)
return self.response
initial Method run perform_authentication
def initial(self, request, *args, **kwargs):
self.format_kwarg = self.get_format_suffix(**kwargs)
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
# Run authentication related methods here
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)
perform_authentication Will the incoming user To verify
def perform_authentication(self, request):
request.user
request Of user Login authentication will be performed
def __init__(self, request, parsers=None, authenticators=None,
negotiator=None, parser_context=None):
assert isinstance(request, HttpRequest), (
'The `request` argument must be an instance of '
'`django.http.HttpRequest`, not `{}.{}`.'
.format(request.__class__.__module__, request.__class__.__name__)
)
self._request = request
self.parsers = parsers or ()
self.authenticators = authenticators or ()
self.negotiator = negotiator or self._default_negotiator()
self.parser_context = parser_context
self._data = Empty
self._files = Empty
self._full_data = Empty
self._content_type = Empty
self._stream = Empty
if self.parser_context is None:
self.parser_context = {
}
self.parser_context['request'] = self
self.parser_context['encoding'] = request.encoding or settings.DEFAULT_CHARSET
force_user = getattr(request, '_force_auth_user', None)
force_token = getattr(request, '_force_auth_token', None)
if force_user is not None or force_token is not None:
forced_auth = ForcedAuthentication(force_user, force_token)
self.authenticators = (forced_auth,)
Two 、 Authority source code analysis
All views are based on APIView
class APIView(View):
# Get authentication configuration
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
#
settings = api_settings
then APIView Of as_view Will run dispatch Method
def dispatch(self, request, *args, **kwargs):
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
# Run here initial To handle authentication
self.initial(request, *args, **kwargs)
return self.response
initial Method run check_permissions
def initial(self, request, *args, **kwargs):
self.format_kwarg = self.get_format_suffix(**kwargs)
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
self.perform_authentication(request)
# Run authentication related methods here
self.check_permissions(request)
self.check_throttles(request)
check_permissions The permission will be verified
def check_permissions(self, request):
# Constantly get permission classes from the permission list and then judge
for permission in self.get_permissions():
if not permission.has_permission(request, self):
self.permission_denied(
request,
message=getattr(permission, 'message', None),
code=getattr(permission, 'code', None)
)
3、 ... and 、 Frequency source code analysis
All views are based on APIView
class APIView(View):
# Get authentication configuration
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
#
settings = api_settings
then APIView Of as_view Will run dispatch Method
def dispatch(self, request, *args, **kwargs):
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
# Run here initial To handle authentication
self.initial(request, *args, **kwargs)
return self.response
initial Method run check_throttles
def initial(self, request, *args, **kwargs):
self.format_kwarg = self.get_format_suffix(**kwargs)
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
self.perform_authentication(request)
self.check_permissions(request)
# Run frequency related methods here
self.check_throttles(request)
check_throttles Access to resources that need to be restricted will be restricted
def check_throttles(self, request):
throttle_durations = []
for throttle in self.get_throttles():
if not throttle.allow_request(request, self):
throttle_durations.append(throttle.wait())
if throttle_durations:
durations = [
duration for duration in throttle_durations
if duration is not None
]
duration = max(durations, default=None)
self.throttled(request, duration)
Four 、 Global exception handling
drf In profile , Already configured , But it's not only for drf Handle the exception of , What we need is to be able to handle all kinds of exceptions , In order to improve the robustness of the code ( Robustness )
drf The default configuration file of the configuration file
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler',
When triggered drf Will be called when the exception error of exception_handler To deal with it
def exception_handler(exc, context):
if isinstance(exc, Http404):
exc = exceptions.NotFound()
elif isinstance(exc, PermissionDenied):
exc = exceptions.PermissionDenied()
if isinstance(exc, exceptions.APIException):
headers = {
}
if getattr(exc, 'auth_header', None):
headers['WWW-Authenticate'] = exc.auth_header
if getattr(exc, 'wait', None):
headers['Retry-After'] = '%d' % exc.wait
if isinstance(exc.detail, (list, dict)):
data = exc.detail
else:
data = {
'detail': exc.detail}
set_rollback()
return Response(data, status=exc.status_code, headers=headers)
return None
Custom global exception handling function
exc For the wrong reason
context For the wrong function Parameters A dictionary composed of pleading
exc: list index out of range
context: {‘view’: <app01.views.UserApiView object at 0x0000024F4D011708>, ‘args’: (), ‘kwargs’: {}, ‘request’: <rest_framework.request.Request: GET ‘/user/’>}
from rest_framework.views import exception_handler
from rest_framework.response import Response
def common_exception_handler(exc, context):
dict_code = {
'code':10001}
response = exception_handler(exc, context)
if response:
dict_code['msg'] = str(exc)
else:
dict_code['code'] = 10002
dict_code['msg'] = str(exc)
return Response(dict_code)
5、 ... and 、 Automatically generate interface documentation
The first one is : Write word、md Submitted to the git On
The second kind : Use the interface document platform , If the company develops itself 、yapi( Baidu open source )、 Third party interface document platform
drf Interface documents are automatically generated in
The automatic generation of interface documents is formed on the basis of automatic routing, that is, in ViewSetMixin Can be achieved on the basis of
Such as coreapi,swagger
coreapi Use steps
1. install pip install coreapi
2. Join the route
from rest_framework.documentation import include_docs_urls
urlpatterns = [
path('docs/', include_docs_urls(title=' Site page title '))
]
3. The configuration file
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
for example :
urls.py
from django.contrib import admin
from django.urls import path
from rest_framework.routers import SimpleRouter
from app01 import views
from rest_framework.documentation import include_docs_urls
router=SimpleRouter()
router.register('book2',views.BookInfoViewSet,'book2')
urlpatterns = [
path('docs/', include_docs_urls(title=' Site page title ')),
path('admin/', admin.site.urls),
path('user/', views.UserApiView.as_view({
'get':'get'})),
]
urlpatterns+=router.urls
views.py
class UserApiView(ViewSetMixin,APIView):
""" get: Return all user information . """
def get(self, request):
l = [1,2]
print(l[1])
return Response({
'coe':'code'})
# Tests that automatically generate interface documents
from rest_framework import generics
class BookListView(generics.ListAPIView):
""" Return all book information . """
class BookListCreateView(generics.ListCreateAPIView):
""" get: Return all book information . post: New books . """
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
""" list: Return book list data retrieve: Return to book details data latest: Return the latest book data read: Revise the amount of books read """
design sketch :
6、 ... and 、RBAC Introduce
RBAC It's role-based access control (Role-Based Access Control ) stay RBAC in , Permissions are associated with roles , Users get access to these roles by becoming members of the appropriate roles .
This greatly simplifies the management of permissions . In this way, management is level dependent , Authority is given to the role , And giving roles to users , This kind of permission design is very clear , It's easy to manage
django The background of admin There is RBAC There is
边栏推荐
- seleniumwire获取百度指数
- [development tutorial 11] crazy shell · open source Bluetooth heart rate waterproof sports Bracelet - explanation of the function code of the whole machine
- Api 接口优化的那些技巧
- Some operations of Ubuntu remote server configuration database (unable to locate package MySQL server, steps of installing mysql, unable to enter password when logging in MySQL)
- Surfacecontrol and surfaceflinger communication
- [develop low code platform] low code rendering
- 17. Design of machine learning system
- 【开发教程11】疯壳·开源蓝牙心率防水运动手环-整机功能代码讲解
- 【愚公系列】2022年07月 Go教学课程 020-Go容器之数组
- Outlier detection and open set identification (2)
猜你喜欢

Outlier detection and open set identification (2)

【飞控开发基础教程8】疯壳·开源编队无人机-I2C(激光测距)

IMG tags prohibit dragging pictures

【开发教程10】疯壳·开源蓝牙心率防水运动手环-蓝牙 BLE 收发

Solutions such as failed plug-in installation and slow speed of linking remote server under vscode
![[micro services ~nacos] Nacos service providers and service consumers](/img/b7/47ecd6979ccfeb270261681d6130be.png)
[micro services ~nacos] Nacos service providers and service consumers

How to solve the problems of MQ message loss, duplication and backlog?

Recursion / backtracking (Part 2)

MySQL sub database and sub table and its smooth expansion scheme

Xinchi technology released the latest flagship product of G9 series, equipped with six A55 cores with 1.8GHz dominant frequency
随机推荐
Flash and seven cattle cloud upload pictures
Introduction and solution of common security vulnerabilities in Web System SQL injection
异步模式之工作线程
Matlab02: structured programming and function definition "suggestions collection"
Camera Hal OEM模块 ---- cmr_preview.c
redis版本怎么查看(查看redis进程)
【esn】 学习回声状态网络
PTA (daily question) 7-74 yesterday
Calculate properties and listeners
PTA (daily question) 7-77 encryption
flask与七牛云上传图片
What are the skills of API interface optimization?
【开发教程10】疯壳·开源蓝牙心率防水运动手环-蓝牙 BLE 收发
Soft test --- database (4) SQL statement
Nftscan and nftplay have reached strategic cooperation in the field of NFT data
Execute immediate simple sample set (DML)
Dynamic programming problem (VII)
Surfacecontrol and surfaceflinger communication
Dynamic programming problem (VIII)
MySQL stored procedure