当前位置:网站首页>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
边栏推荐
- 还在写大量 if 来判断?一个规则执行器干掉项目中所有的 if 判断...
- How to learn R language
- Calculate properties and listeners
- Minimum dominating set (MDS) and its matlab code
- The download file of native JS implementation can be used anywhere
- Locally connect to redis on Windows Server
- 时间序列统计分析
- @Detailed explanation of postconstruct annotation
- 17. Design of machine learning system
- 数学建模及其基础知识详解(化学常考知识点)
猜你喜欢
[ESN] learning echo state network
2022dasctfjuly empowerment competition (reappearance)
Alibaba Code代码索引技术实践:为Code Review提供本地IDE的阅读体验
Alibaba code index technology practice: provide reading experience of local IDE for code review
IMG tags prohibit dragging pictures
Dynamic programming problem (6)
Teach you how to install latex (nanny level tutorial)
"Food alliance ordering system"
Anomaly detection and unsupervised learning (1)
Outlier detection and open set identification (2)
随机推荐
Application and principle of distributed current limiting redistribution rratelimiter
requestVideoFrameCallback() 简单实例
聊聊异步编程的 7 种实现方式
软考 --- 数据库(4)SQL语句
[develop low code platform] low code rendering
@Detailed explanation of the use of transactional annotation
【MySQL 8】Generated Invisible Primary Keys(GIPK)
ZABBIX deployment and monitoring
Nftscan and nftplay have reached strategic cooperation in the field of NFT data
Download the latest version of visual studio code and connect to the server remotely (very detailed)
PTA (daily question) 7-74 yesterday
I don't recommend you use Select*
PTA (daily question) 7-75 how many people in a school
第二轮1000个Okaleido Tiger,再次登录Binance NFT 1小时售罄
[untitled]
[basic course of flight control development 8] crazy shell · open source formation uav-i2c (laser ranging)
Router view cannot be rendered (a very low-level error)
PTA (daily question) 7-71 character trapezoid
Outlier detection and Gan network (1)
Table custom style row class name in elemenui