# Course link
4 Sky fix django rest framework Source code and actual combat _ Bili, Bili _bilibili
# Course content
(1)rest framework User login of
(2)rest framework Based on token Implement basic user authentication
(3)rest framework Source code analysis of the basic authentication process
(4)rest framework Anonymous user configuration
(5)rest framework Built in basic authentication
(6)rest framework Summary of certification content of
(7)rest framework The basic use of permissions
【 Supplementary knowledge 】
# Today's wine is today's wine
# (1) User login and topics in this section
1)token Random string . This is to use the front end to send user information to the back end , Then the back end generates a random string , namely token. This token It can be placed in the request header or url above , It's better to put it in url On , This avoids cross domain issues . So this url Like the picture below .
2) The theme of this section .
# (2) The implementation of user login .
1) Create table data , Used to simulate the process . because username Only one user can correspond to one user name , therefore UerInfo Below the table username Attributes are the only .
2) After designing the user table , Let's start writing view functions , To simulate the process of user login . In conclusion, it is , The user sends a user name and password request to the backend , After receiving, the backend will check in the database , If the verification has users , It will generate a token Save in UserToken Table below , And will token Return to the user . The code is as follows .
3)token Generation . It's used here md5 Encrypted method to generate , And every time, no matter whether the user carries it or not token visit , The back end will generate a new token. The encrypted code is as follows :
4)postman Test results
# (1) User authentication
1) Some pages must be logged in by the user , To operate . For example, we re create a route for the order business , Write the corresponding view class . Our idea is to judge the incoming user request , With or without token , If a token, It means that the user has logged in .
2) There are two ways to realize this idea ( Yes, of course , There are more convenient ). The first method is to set a judgment directly in each function token The logic of , Very troublesome . The following is the validation function post Request part , The code logic we added .
# Test data ORDER_DICT = { 1: { "name": "lolo", "age": 12, "gender": " male " }, 2: { "name": "bobo", "age": 14, "gender": " male " } } class OrderView(APIView): """ Order business """ def get(self, request, *args, **kwargs): # The order page can only be viewed by logged in users , Obviously, you just need to check whether the user has brought the... When sending the request token that will do . # Based on this idea , We can choose two ways to achieve . # (1) The first is to write a judgment for each function . # (2) The second is based on drf Provides a way to write # Here is the first token = request._request.GET.get("token") if not token: # If token It's empty , Then return to the user who is not logged in return HttpResponse(" The user is not logged in ") ret = {'code': 1000, 'msg': None, 'data': None} try: ret['data'] = ORDER_DICT except Exception as e: pass return JsonResponse(ret)
3) be based on drf Implementation of the validation process . The first thing to know is , If you want to use drf Source code of the flow of authentication_classes, This list class contains validation rules . This rule can be made by ourselves . So the specific use , It just has to be in every function , Configure the list class in advance , For example, we define a validation rule whose class name is Authentication, So when we want to use , Is to make authentication_classes = [ Authentication,] . In short, it was written like this first , The following chapters can be done by looking at the source code .
class OrderView(APIView): """ Order business """ # drf Of authentication_classes Certification Rules , If we want to use drf The login verification function is provided , # You need to add corresponding rules to authentication_classes, Then this rule , It can be customized by us authentication_classes = [Authentication, ] def get(self, request, *args, **kwargs): # The order page can only be viewed by logged in users , Obviously, you just need to check whether the user has brought the... When sending the request token that will do . # Based on this idea , We can choose two ways to achieve . # (1) The first is to write a judgment for each function . # (2) The second is based on drf Provides a way to write ret = {'code': 1000, 'msg': None, 'data': None} try: ret['data'] = ORDER_DICT except Exception as e: pass return JsonResponse(ret)
4) Here is the code of the validation rule class . Specific notes
from rest_framework import exceptions class Authentication(object): def authenticate(self, request): token = request._request.GET.get("token") token_obj = models.UserToken.objects.filter(token=token).first() if not token_obj: # If there is no corresponding token Then throw an exception , This exception is drf Self contained , It must also be written like this raise exceptions.AuthenticationFailed(" User authentication failed ") # If the authentication is successful , Just return the following two values , In the form of a meta group , This is for follow-up drf The internal source code uses # The specific thing is to self._authenticate() Function user_auth_tuple Use return (token_obj.user, token_obj.token) def authenticate_header(self, request): """ Because the defined validation class must have this method , For a while , I'll say later .""" pass
# (1) Martial sir To the source flow
# (2) My own analysis of the certification source code process
# (1) Global configuration
1) We can see , We are the first (2) In the section , Configuration rule class authentication_classes = [Authentication, ], This only applies to the current OrderView Class . For other classes, if this rule class is not configured , Will not use . It is equivalent to local configuration . How to perform global configuration ( That is, even if all view classes are not configured authentication_classes , We can also use our custom rule classes ), The following steps are required . First go to settings.py , Write... At the bottom REST_FRAMEWORK = {} , As follows :
# (2) Separate local configurations
1) Based on the above configuration operations, you can set , The global view class is authenticated according to our custom rules . Of course, some view classes do not require this authentication , We can set the rule list separately , This is how to configure the view class ( That is, local configuration ), As shown in the red box below .
# (1) Built in basic authentication rules
1)drf Basic authentication rules are built in , such as BaseAuthentication() This built-in class . The import module from rest_framework.authentication import BaseAuthentication You can use it () That is to say rest_framework Of authentication In file .【 Here we explain why you can customize rules , must authenticate_header() Method 】
# (2) A small summary
【 review 】 Links to this lesson :4 Sky fix django rest framework Source code and actual combat _ Bili, Bili _bilibili
# (1) Content summary
# (1) Basic use of permissions
1) Actually drf The process of using permissions in is similar to the previous authentication process , And the corresponding overall situation / Local configurations are similar . For example, we want to follow the type of users , To determine whether the user has access to a view page . Getting the type of user is simple , Namely request.user.user_type , Like the following code , We make a judgment on each view class , This is obviously troublesome .
2)drf The authority authentication method provided , In fact, when applied , It is similar to the rule class of user authentication .
3) Specific code , We can also see that , If we want to apply custom permission rules to a view class , It can be the same as the previous user authentication rule configuration . As for global configuration , See the source code analysis in the following section .
Reference link :4 Sky fix django rest framework Source code and actual combat _ Bili, Bili _bilibili
【 Supplementary knowledge 】
# (1)csrf Principle
In fact, it is the second section of this article . The whole process is after the user logs in , The server returns a to the user Random string token , The next time the user visits , Just take token Come on , If the server matches token Through , Otherwise access is denied .
Reference material :15 God django Entry to give up _ Bili, Bili _bilibili