VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Python基础教程 >
  • python基础教程之从cbv到fbv:用函数写视图与用类写视图的区别(drf与restful)

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/pythonxin3721/


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('删除订单')
相关教程