pip3 install djangorestframework
from rest_framework.views import APIView # rest_framework框架,继承View
class ApiTest(APIView):
pass
def dispatch(self, request, *args, **kwargs): self.args = args self.kwargs = kwargs # 这里用initalize_request方法对原生的request进行加工 request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: # 对加工之后的request处理,看下这里边的逻辑 self.initial(request, *args, **kwargs) if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response
def initialize_request(self, request, *args, **kwargs): """ Returns the initial request object. """ parser_context = self.get_parser_context(request) return Request( request, parsers=self.get_parsers(), authenticators=self.get_authenticators(), negotiator=self.get_content_negotiator(), parser_context=parser_context )
def get_authenticators(self): """ Instantiates and returns the list of authenticators that this view can use. """ return [auth() for auth in self.authentication_classes]
class APIView(View): # The following policies may be set at either globally, or per-view. renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES parser_classes = api_settings.DEFAULT_PARSER_CLASSES authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES #这里 throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS metadata_class = api_settings.DEFAULT_METADATA_CLASS versioning_class = api_settings.DEFAULT_VERSIONING_CLASS
from rest_framework.authentication import BasicAuthentication class ApiTest(APIView): authentication_classes = [BasicAuthentication]
def dispatch(self, request, *args, **kwargs): self.args = args self.kwargs = kwargs # 这里用initalize_request方法对原生的request进行加工 request = self.initialize_request(request, *args, **kwargs) self.request = request # 赋值 self.headers = self.default_response_headers # deprecate?
------------------------------------------------------------------------------------------- try: # 对加工之后的request处理,看下这里边的逻辑 self.initial(request, *args, **kwargs) if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response
def initial(self, request, *args, **kwargs): """ Runs anything that needs to occur prior to calling the method handler. """ self.format_kwarg = self.get_format_suffix(**kwargs)
......
self.perform_authentication(request) # 封装过数据之后的request,认证用 self.check_permissions(request) self.check_throttles(request)
@property def user(self): """ Returns the user associated with the current request, as authenticated by the authentication classes provided to the request. """ if not hasattr(self, ‘_user‘): with wrap_attributeerrors(): self._authenticate() # 查看下这个方法 return self._user
def _authenticate(self): """ Attempt to authenticate the request using each authentication instance in turn. """ for authenticator in self.authenticators: # 之前封装的认证对象 try: user_auth_tuple = authenticator.authenticate(self) # 认证是否登录的方法,成功返回元组,失败报错 except exceptions.APIException: self._not_authenticated() raise if user_auth_tuple is not None: self._authenticator = authenticator self.user, self.auth = user_auth_tuple return self._not_authenticated()
from django.shortcuts import HttpResponse import json from rest_framework.views import APIView # rest_framework框架,继承View from rest_framework.authentication import BasicAuthentication from rest_framework import exceptions # 验证失败触发异常 class Myauthentication(object): def authenticate(self, request): username = request._request.GET.get("username") # 验证成功返回元组 if not username: raise exceptions.AuthenticationFailed("用户名未登录") # 无返回验证失败,触发异常 return ("status",1) def authenticate_header(self, val): pass class ApiTest(APIView): authentication_classes = [Myauthentication] # 通过自定义的类做认证 def get(self, request, *args, **kwargs): # 用于处理get请求 print(request) res = { "code": 1000, "msg": "hello world" } return HttpResponse(json.dumps(res)) def post(self, request, *args, **kwargs): return HttpResponse("post") def put(self, request, *args, **kwargs): return HttpResponse("put") def delete(self, request, *args, **kwargs): return HttpResponse("delete")
原文:https://www.cnblogs.com/ligiao/p/11493814.html