一、restframework的安装
方式一:pip3 install djangorestframework
方式二:pycharm图形化界面安装
方式三:pycharm命令行下安装(装在当前工程所用的解释器下)
二、基于Django实现的API(不带restframework)
FBV
1 from django.shortcuts import render,HttpResponse 2 3 # Create your views here. 4 import json 5 6 def users(request): 7 response = {'code':1000,'data':None} #code用来表示状态,比如1000代表成功,1001代表 8 response['data'] = [ 9 {'name':'haiyan','age':22}, 10 {'name':'haidong','age':10}, 11 {'name':'haixiyu','age':11}, 12 ] 13 return HttpResponse(json.dumps(response)) #返回多条数据 14 15 def user(request,pk): 16 if request.method =='GET': 17 return HttpResponse(json.dumps({'name':'haiyan','age':11})) #返回一条数据 18 elif request.method =='POST': 19 return HttpResponse(json.dumps({'code':1111})) #返回一条数据 20 elif request.method =='PUT': 21 pass 22 elif request.method =='DELETE': 23 pass 24 25 views
CBV
from django.views import View class UsersView(View): def get(self,request): response = {'code':1000,'data':None} response['data'] = [ {'name': 'haiyan', 'age': 22}, {'name': 'haidong', 'age': 10}, {'name': 'haixiyu', 'age': 11}, ] return HttpResponse(json.dumps(response),stutas=200) class UserView(View): def get(self,request,pk): return HttpResponse(json.dumps({'name':'haiyan','age':11})) #返回一条数据 def post(self,request,pk): return HttpResponse(json.dumps({'code':1111})) #返回一条数据 def put(self,request,pk): pass def delete(self,request,pk): pass views
三、restframework里封装的APIView分析
基于django实现的API许多功能都需要我们自己开发,这时候djangorestframework就给我们提供了方便,直接基于它来返回数据,总之原理都是一样的,就是给一个接口也就是url,让前端的人去请求这个url去获取数据,在页面上显示出来。这样也就达到了前后端分离的效果。
as_view方法
1 @classmethod 2 def as_view(cls, **initkwargs): 3 """ 4 Store the original class on the view function. 5 6 This allows us to discover information about the view when we do URL 7 reverse lookups. Used for breadcrumb generation. 8 """ 9 if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet): 10 def force_evaluation(): 11 raise RuntimeError( 12 'Do not evaluate the `.queryset` attribute directly, ' 13 'as the result will be cached and reused between requests. ' 14 'Use `.all()` or call `.get_queryset()` instead.' 15 ) 16 cls.queryset._fetch_all = force_evaluation 17 18 view = super(APIView, cls).as_view(**initkwargs) 19 view.cls = cls 20 view.initkwargs = initkwargs 21 22 # Note: session based authentication is explicitly CSRF validated, 23 # all other authentication is CSRF exempt. 24 return csrf_exempt(view) 25 26 as_view方法
dispatch方法
1 def dispatch(self, request, *args, **kwargs): 2 """ 3 `.dispatch()` is pretty much the same as Django's regular dispatch, 4 but with extra hooks for startup, finalize, and exception handling. 5 """ 6 self.args = args 7 self.kwargs = kwargs 8 request = self.initialize_request(request, *args, **kwargs) 9 self.request = request 10 self.headers = self.default_response_headers # deprecate? 11 12 try: 13 self.initial(request, *args, **kwargs) 14 15 # Get the appropriate handler method 16 if request.method.lower() in self.http_method_names: 17 handler = getattr(self, request.method.lower(), 18 self.http_method_not_allowed) 19 else: 20 handler = self.http_method_not_allowed 21 22 response = handler(request, *args, **kwargs) 23 24 except Exception as exc: 25 response = self.handle_exception(exc) 26 27 self.response = self.finalize_response(request, response, *args, **kwargs) 28 return self.response 29 30 dispatch
initialize_request
1 def initialize_request(self, request, *args, **kwargs): 2 """ 3 Returns the initial request object. 4 """ 5 parser_context = self.get_parser_context(request) 6 7 return Request( 8 request, 9 parsers=self.get_parsers(), 10 authenticators=self.get_authenticators(), 11 negotiator=self.get_content_negotiator(), 12 parser_context=parser_context 13 ) 14 15 initialize_request
initial方法(内部调用认证,权限和频率)
1 def initial(self, request, *args, **kwargs): 2 """ 3 Runs anything that needs to occur prior to calling the method handler. 4 """ 5 self.format_kwarg = self.get_format_suffix(**kwargs) 6 7 # Perform content negotiation and store the accepted info on the request 8 neg = self.perform_content_negotiation(request) 9 request.accepted_renderer, request.accepted_media_type = neg 10 11 # Determine the API version, if versioning is in use. 12 version, scheme = self.determine_version(request, *args, **kwargs) 13 request.version, request.versioning_scheme = version, scheme 14 15 # Ensure that the incoming request is permitted 16 self.perform_authentication(request) 17 self.check_permissions(request) 18 self.check_throttles(request) 19 20 initial方法(内部调用认证,权限和频率)