FBV 基於函數的視圖 (function base views) CBV 基於類的視圖 (class base views) 也就是說我們是用函數編寫視圖~還是類編寫視圖~~我們來看下兩個的簡單實現~~ urlpatterns = [ path(‘admin/‘, admin.site.urls) ...
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('刪除訂單')