path('dog/', views.DogView.as_view())
from django.views import View
from rest_framework.views import APIView
class DogView(APIView):
''' according to APIView Source code , It can be seen that he inherited from django Of View, This APIView The inside of the class dispatch() function , Has been restframework Modified , The functions inside are increased A lot , Handed over request Parameters are also processed '''
def get(self,request, *args, **kwargs):
ret = {
'code': 1000,
'msg': 'xxx'
}
return HttpResponse(json.dumps(ret), status=201)
def post(self, request, *args, **kwargs):
return HttpResponse(" establish dog")
def put(self, request, *args, **kwargs):
return HttpResponse(' to update dog')
def delete(self, request, *args, **kwargs):
return HttpResponse(' Delete dog')
So after restframework Of APIView after ,request, Changed , Added some validation classes , Parser , Class of current limiting measures , These classes can be configured to use , It can also be set without , It's useless without setting .
Click here to see Request() The type of : As shown in the figure below :
Put the request, parsers, authen…, nego…, parser_c… Pass it as a parameter to the Request() class , After initialization in this class , Return to the picture above initialize_request()
And you can see that Request The structure of parameters and functions in the class is as follows :
We can always see user, data, auth, content_type wait
Take it here alone authenticators=self.get_authenticators() To find the corresponding function .
You can see the picture below here : So after processing request There are instances of authorized classes , And more than one , There are many , They form a list . It's actually a list , It's just that every item in this list is an instance of a class . Don't think it's complicated .
From the above picture, you can see the self.authentication_classes This thing , Click again , Jump to APIView The beginning of is as follows : Note here is actually reading restframework Class instances in the configuration file .
To sum up, we can see , Use restframework Of apiview after ,request After packaging , It integrates some other functions , These functions exist in the form of classes , It can be set in the configuration file setttings.py in ( Because the last end is in the configuration file ), It can also be set in our handwriting views.py in , Or introduce into views.py In the middle , Because once we write our own related classes , And instantiate it , The program will be written by us views.py Find relevant class instances in this level . Why , In fact, it's because of class inheritance , If we write it ourselves , You won't find it in the parent class , If we don't write , because APIView It's because of class , So I will look up .
So for some permissions , authentication , Current limiting , We can use restframwork These mechanisms of , Implemented directly in the class , Then introduce the views.py in , Or directly at views.py Write in . You can achieve these functions . Don't use django The middleware implemented .
Looking at the picture below :
Look at the picture above , Click on self.perform_authentication(request), Go to the function above the picture below :
Look at the picture above : We went to the Request() Look for user attribute , Here's the picture :
Look at the picture above : Find out authenticate() Function does not write any logic code , So if we customize Verification type words , You have to rewrite this method . Implement your own login verification logic .
Below class MyAuthentication() That is, we generally realize restframework Basic operation of certification , Is to write a class , Rewrite two methods , Write the logic of authentication , And then in views Just quote in , If there are more than one, enter them in the form of a list , Then this views.py You will validate the validation classes in the list one by one .
So if there are multiple validation rules , It can be split into multiple classes , And then in views Just enclose it in a list .
from django.shortcuts import render
from django.http import HttpResponse
import json
from rest_framework.authentication import BasicAuthentication
from rest_framework import exceptions
###########restframework The authorized part ##################
from django.views import View
from rest_framework.views import APIView
# Here we try to write a verification class by ourselves , rewrite authenticate() Method , Implement your own authentication logic
# browser url --> http://127.0.0.1/dog/?token=123 This 123 Is random , This url You can successfully return get() The code in the function .
class MyAuthentication(object):
def authenticate(self, request): # rewrite authenticate() Method , Implement your own authentication logic
token = request._request.GET.get('token') # The first one here request After encapsulation and integration request, the second _request It's original. request. Reference here Request() class .
# Here's an example , Suppose the user requests , Verify with or without token, If you bring it, return to Yuanzu , This return primitive is required by the validation class ,(user, token)
# You can get the user name and password of the user login , Then go to the database to verify , This is not done here
if not token:
raise exceptions.AuthenticationFailed(' User authentication failed ') # Suppose there is no token, Return user authentication failure .
return ('lxbai', None) # This is after the verification is successful , The returned user name and token The tuples , We can do that view Print it out to see if it is
def authenticate_header(self, request):
""" Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """
pass
class DogView(APIView):
''' according to APIView Source code , It can be seen that he inherited from django Of View, This APIView The inside of the class dispatch() function , Has been restframework Modified , The functions inside are increased A lot , Handed over request Parameters are also processed '''
authentication_classes = [MyAuthentication,]
print(request.user) # Print the contents of Yuanzu returned after we call the verifier , It's the one above lixbai
def get(self,request, *args, **kwargs):
ret = {
'code': 1000,
'msg': 'xxx'
}
return HttpResponse(json.dumps(ret), status=201)
def post(self, request, *args, **kwargs):
return HttpResponse(" establish dog")
def put(self, request, *args, **kwargs):
return HttpResponse(' to update dog')
def delete(self, request, *args, **kwargs):
return HttpResponse(' Delete dog')