从cbv到fbv:用函数写视图与用类写视图的区别(drf与restful)

FBV 基于函数的视图 (function base views)

CBV 基于类的视图 (class base views)

也就是说我们是用函数编写视图~还是类编写视图我们来看下两个的简单实现

urlpatterns = [
path(‘admin/‘, admin.site.urls),
path(‘test_fbv‘, test_fbv), #FBV
path(‘test_cbv‘, TestCBV.as_view()) #CBV]
def test_fbv(request): ##函数式视图
return HttpResponse("ok")

class TestCBV(View): ##类式视图
def get(self, request):
return HttpResponse("ok")
CBV会执行as_view()方法,

a. 接口开发

        urlpatterns = [
            # url(r'^admin/', admin.site.urls),
            url(r'^get_order/', views.get_order),
            url(r'^add_order/', views.add_order),
            url(r'^del_order/', views.del_order),
            url(r'^update_order/', views.update_order),
        ]
        
            
        def get_order(request):
            return HttpResponse('')


        def add_order(request):
            return HttpResponse('')


        def del_order(request):
            return HttpResponse('')


        def update_order(request):
            return HttpResponse('')
            

b. restful 规范(建议)

           1. 根据method不同做不同的操作,示例:
        
           基于FBV:
                urlpatterns = [
                    url(r'^order/', views.order),
                ]

                def order(request):
                    if request.method == 'GET':
                        return HttpResponse('获取订单')
                    elif request.method == 'POST':
                        return HttpResponse('创建订单')
                    elif request.method == 'PUT':
                        return HttpResponse('更新订单')
                    elif request.method == 'DELETE':
                        return HttpResponse('删除订单')
            基于CBV:
                urlpatterns = [
                    url(r'^order/', views.OrderView.as_view()),
                ]
        
                class OrderView(View):
                    def get(self,request,*args,**kwargs):
                        return HttpResponse('获取订单')

                    def post(self,request,*args,**kwargs):
                        return HttpResponse('创建订单')

                    def put(self,request,*args,**kwargs):
                        return HttpResponse('更新订单')

                    def delete(self,request,*args,**kwargs):
                        return HttpResponse('删除订单')
上一篇:django FBV&&CBV upload-file json 路由系统 反向解析


下一篇:FBV/CBV