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

阿里云2000元红包!本站用户参与享受九折优惠!

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(‘删除订单’)https://www.cnblogs.com/ayongxin93/p/11924574.html

「点点赞赏,手留余香」

    还没有人赞赏,快来当第一个赞赏的人吧!
0 条回复 A 作者 M 管理员
    所有的伟大,都源于一个勇敢的开始!
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论