django API 接口 (CBV FBV)

前言

django api接口 有两种模式,一个是FBV,另一个是CBV。首要推荐的是CBV 模式。

FBV 模式的API 接口

使用函数,通过if/else 语句根据请求方法进行数据返回/接口。

from django.shortcuts import render,HttpResponse
import json
from django.views.decorators.csrf import csrf_exempt

# Create your views here.


@csrf_exempt                   #对此试图函数添加csrf装饰器,使得此函数的post请求免验证tooken
def Asset(request):
    if request.method == "POST":
        info = json.loads(request.body.decode('utf-8'))
        print(info)
        return HttpResponse('收到了')
    else:
        host_list = ['c1.com', 'c2.com', 'c3.com']
        return HttpResponse(json.dumps(host_list))
View Code

CBV 模式中的传统方式

cbv中遇到希望给方法添加普通的装饰器时

                urls.py
                    from django.conf.urls import url
                    from api import views

                    urlpatterns = [
                        url(r'^asset/$',views.AssetView.as_view()),
                    ]
                    
                views.py
                    import json
                    from django.shortcuts import render,HttpResponse
                    from django.views.decorators.csrf import csrf_exempt
                    from django.utils.decorators import method_decorator
                    from django.views import View

                    class AssetView(View):
                        """
                        资产相关接口
                        """
                        @method_decorator(x1)                    #x1为希望添加的装饰器
                        def get(self,requset,*args,**kwargs):
                            host_list = ['c1.com', 'c2.com', 'c3.com']
                            return HttpResponse(json.dumps(host_list))

                        @method_decorator(x2)
                        def post(self,request,*args,**kwargs):
                            info = json.loads(request.body.decode('utf-8'))
                            print(info)
                            return HttpResponse('收到了')
View Code

cbv中要给方法添加的装饰器为 csrf_exempt时的添加方法

urls.py
                        from django.conf.urls import url
                        from api import views

                        urlpatterns = [
                            # url(r'^asset/$',views.asset),
                            url(r'^asset/$',views.AssetView.as_view()),
                        ]
                    views.py                
                        import json
                        from django.shortcuts import render,HttpResponse
                        from django.views.decorators.csrf import csrf_exempt
                        from django.utils.decorators import method_decorator
                        from django.views import View
                        
                        # 方式一
                        @method_decorator(csrf_exempt,name='dispatch')
                        class AssetView(View):                #必须要继承View
                            """
                            资产相关接口
                            """
                            # 方式二(在get/post方法上面添加如下代码)
                            # @method_decorator(csrf_exempt)
                            # def dispatch(self, request, *args, **kwargs):
                            #     return super().dispatch(request, *args, **kwargs)

                        
                            def get(self,requset,*args,**kwargs):
                                host_list = ['c1.com', 'c2.com', 'c3.com']
                                return HttpResponse(json.dumps(host_list))


                            def post(self,request,*args,**kwargs):
                                info = json.loads(request.body.decode('utf-8'))
                                print(info)
                                return HttpResponse('收到了')
View Code

CBV模式中的rest framework 方式

优点:1、 自动加 csrf_exempt   2、 页面变好看(替代Httprespose,返回更好的页面)   3、 自动反序列化(无需使用json 对数据进行dumps/loads)

先注册app在django 的settings.py 中

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]
View Code

urls.py

from django.conf.urls import url
from api import views

urlpatterns = [
    # url(r'^asset/$',views.asset),
    url(r'^asset/$',views.AssetView.as_view()),
]
View Code

views.py

                    from rest_framework.views import APIView
                    from rest_framework.response import Response
                    #无需添加csrf_exempt 内部已经做了处理
                    class AssetView(APIView):
                        def get(self, requset, *args, **kwargs):
                            host_list = ['c1.com', 'c2.com', 'c3.com']
                            # return HttpResponse(json.dumps(host_list))
                            #Response 返回数据时会把数据嵌套在注册的app rest_framewor中的模板中展示并返回给浏览器
                            return Response(host_list)

                        def post(self, request, *args, **kwargs):
                            #无需数据解码,数据的反序列化
                            print(request.data)                         #json格式
                            return HttpResponse('收到了')
View Code

总结:

相比较而言,最推荐的是 rest  framework 的CBV 模式,优点:1、 自动加 csrf_exempt   2、 页面变好看(替代Httprespose,返回更好的页面)   3、 自动反序列化(无需使用json 对数据进行dumps/loads)

 

posted @ 2019-01-21 22:29  fanggege  阅读(756)  评论(0编辑  收藏  举报