Django FBV与CBV 的认识

FBV :function base views,Django在视图里用函数处理请求。

例如:使用GET请求获取城市信息,我们在函数处理的时候,需要对HTTP请求的方式需要先进行判断,然后在进行不同的处理。

from Django.http import JsonResponse
from models import City
def FBView(request):
    if request.method == 'GET':
        id = request.GET.get('c_id')

        city = City.objects.get(id=id)
        data = {
            'id': city.id,
            'code': city.citycode,
            'letter': city.first_letter,
            'region_name': city.regionname,
            'pinyin': city.pinyin,

        }

        return JsonResponse({'msg': 'ok', 'data': data, 'status_code': 200})

结果:

CBV:class base views ,Django在视图里使用处理请求。

好处:1,OOP的编程方式,提高了代码的复用行

           2,不需要像FBV那样,处理不同请求的时候加许多if语句;

CBV提供了一个as_view()静态方法(也就是类方法),调用这个方法,会创建一个类的实例,然后通过实例调用dispatch()方法,dispatch()方法会根据request的method的不同调用相应的方法来处理request(如get() , post()等)

url注册:

from restapp.views import TestView

#CBV提供了一个as_view()的类方法

urlpatterns = [

    path('testview/', TestView.as_view()),

]

视图里使用类,继承自django 里的View,可以根据需要写不同的需求。

大体就是由url路由到这个cbv之后,通过cbv内部的dispatch方法进行分发,将get请求分发给cbv.get方法处理

from django.views import View



class TestView(View):

    def get(self, request, *args, **kwargs):

        id = request.GET.get('c_id')

        city = City.objects.get(id=id)

        data = {

            'id': city.id,

            'code': city.citycode,

            'letter': city.first_letter,

            'region_name': city.regionname,

            'pinyin': city.pinyin,

        }

        return JsonResponse({'msg': 'ok', 'data': data, 'status_code': 200})



    def post(self, request, *args, **kwargs):

        id = request.POST.get('c_id')

        city = City.objects.get(id=id)

        data = {

            'id': city.id,

            'code': city.citycode,

            'letter': city.first_letter,

            'region_name': city.regionname,

            'pinyin': city.pinyin,


        }

        return JsonResponse({'msg': 'ok', 'data': data, 'status_code': 200})

结果1:get请求

结果2:post 请求

猜你喜欢

转载自blog.csdn.net/qq_32903613/article/details/88115807