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 请求

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值