Python - Django - FBV 和 CBV

FBV:

Function Base View,基于函数的视图

views.py:

from django.shortcuts import render, HttpResponse


# FBV
def upload(request):
    if request.method == "POST":
        filename = request.FILES["upload_file"].name
        with open(filename, "wb") as f:
            for chunk in request.FILES["upload_file"].chunks():
                f.write(chunk)
        return HttpResponse("上传OK")
    else:
        return render(request, "upload.html")

urls.py:

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

urlpatterns = [
    url(r'^upload/', views.upload),  # FBV
]

 

CBV:

Class Base View,基于类的视图

CBV 需要继承 Views,当有请求时,先执行 dispatch 函数,然后对请求方式的函数进行反射。例如,如果是 get 请求就执行类中的 get 函数

views.py:

from django.shortcuts import render, HttpResponse
from django.views import View  # CBV 需要继承


# CBV
class Upload(View):
    # 定义 get 函数,用于处理 get 请求
    def get(self, request):
        return render(request, "upload.html")

    # 定义 post 函数,用于处理 post 请求
    def post(self, request):
        filename = request.FILES["upload_file"].name
        with open(filename, "wb") as f:
            for chunk in request.FILES["upload_file"].chunks():
                f.write(chunk)
        return HttpResponse("上传OK")

urls.py:

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

urlpatterns = [
    # url(r'^upload/', views.upload),  # FBV
    url(r'^upload/', views.Upload.as_view()),  # CBV
]

 用 CBV 需要加上一个 .as_view()

posted @ 2019-07-30 17:50  Sch01aR#  阅读(220)  评论(0编辑  收藏  举报