什么是FBV和CBV?

在早期,视图开发的过程中存在一些常见的语法和模式,于是引入基于函数的通用视图来抽象这些模式,并简化了常见情况下的视图开发。因此,刚开始的时候只有FBV,而Django所做的事情就是向你定义的视图函数传递一个HttpRequest,并且希望返回一个HttpResponse。但是,基于函数的通用视图是有问题的,问题在于它很好地覆盖了简单的情况,但针对稍微复杂的场景,它没有办法在某些配置项之外进行扩展或自定义,从而极大地限制了它在许多实际应用程序中的实用性。而考虑到扩展性与自定义,这正是面向对象技术的强大之处,于是诞生了CBV。

基于类的通用视图与基于函数的通用视图目的都一样,都是为了让视图开发更加容易。但是CBV的解决方案是通过使用mixins,并且django内置了一系列通用视图作为工具集提供给我们继承使用,从而使得基于类的通用视图比基于函数的通用视图更具扩展性和灵活性。Django View视图是可调用的,用来处理请求(request)并且返回响应(response),Django的视图有两种形式:FBV和CBV。那么,什么是FBV和CBV编程模式呢?下面我们就一起通过实例来看看。

我们知道 Python 是一个门面向对象的编程语言。如果我们只用函数来编写视图函数,那么就会造成很多面向对象的优点无法利用起来,比如说封装、继承、多态等。这也是 Django 之所以加入了 CBV 模式的原因。它可以让开发者使用类的形式去编写 View 视图函数。对于使用 CBV 模式优势总结了如下几点:

  • CBV 将整个视图函数的逻辑拆成了类下的多个函数,依靠函数调用来实现完整的逻辑;
  • 提高代码的可复用性,更加灵活,让开发者使用面向对象的技术,比如多继承、多态等;
  • 可以用不同的函数针对不同的 HTTP 方法处理,而不是通过很多 if 判断,提高代码可读性。

当然 CBV 也不是万能的,当继承关系变得很复杂,亦或是代码不是特别规整的时候,这时要去找某一个函数到底是被哪一个父类重载也是一个麻烦事。此时使用 FBV 模式就变的很方便,所以还是要理解它们两者的区别,在合适的场景选用合适的方法,不能把其中某一种模式视为唯一。总体上来说 CBV 的模式,在实际的开发工作中使用的相对较多,所以我们要掌握这种编写 view 视图函数的模式。

FBV(基于函数的视图)

FBV(function based views),即基于函数的视图;CBV(class based views);也是基于对象的视图。说白了就是在每一个views中添加自己专用的方法。FBV 简单易懂,但是难以复用。它们不能像 CBV 那样能从父类中继承。FBV 的编写指南要求我们:视图代码越少越好;视图代码不能重复;视图应该只处理呈现逻辑。业务逻辑应尽可能放在数据模型中,或者表单对象中;视图代码要保持简单;使用它们来编写自定义的 403, 404, 500 等错误处理器;避免使用嵌套的 if 块。CBV是View类的集成类;这里的主要区别在于请求是以HTTP方法命名的类方法内处理的,例如GET ,POST ,PUT ,HEAD等。所以,在这里,我们不需要做一个条件来判断请求是一个 POST 还是它是一个 GET 。代码会直接跳转到正确的方法中,在 View 类中内部处理了这个逻辑。

我们首先在Django项目的URL中添加如下内容urls.py:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/$', account.login),
]

添加完成之后我们通过FBV来写一个简单的Login登录模块(views.py):

# 登录验证
def login(request):
    message = ""

    if request.method == "POST":
        user = request.POST.get('username')
        pwd = request.POST.get('password')
        c = Administrator.objects.filter(username=user, password=pwd).count()
        if c:
            request.session['is_login'] = True
            request.session['username'] = user
            return redirect('/index.html')
        else:
            message = "用户名或密码错误"

    return render(request, 'login.html', {'msg': message})

简单讲,FBV就是在views.py文件中定义函数来处理用户请求,函数中再定义如果是GET请求怎么处理,POST请求怎么处理,等等!

CBV(基于类的视图)

CBV是基于类的视图,就是使用了类来处理用户的请求,不同的请求我们可以在类中使用不同方法来处理,这样大大的提高了代码的可读性。CBV允许我们使用不同的实例方法来响应不同的HTTP请求方法,而不是像FBV那样使用条件分支代码。但是定义的类要继承父类View,所以我们在使用CBV的时候需要提前引入库:from django.views import View

执行对应请求的方法前会优先执行 dispatch 方法(在get/post/put…方法前执行),dispatch() 方法会根据请求的不同调用相应的方法来处理。其实,在我们前面学到的知识都知道 Django 的 url 是将一个请求分配给可调用的函数的,而不是一个类,那是如何实现基于类的视图的呢? 主要还是通过父类 View 提供的一个静态方法 as_view() ,as_view 方法是基于类的外部接口, 他返回一个视图函数,调用后请求会传递给 dispatch 方法,dispatch 方法再根据不同请求来处理不同的方法。

我们首先在Django项目的URL中添加如下内容urls.py:

urlpatterns = [
    path("login/", views.Login.as_view()),
]

添加完成之后我们通过CBV来写一个简单的GET和POST方法(views.py):

from django.shortcuts import render,HttpResponse
from django.views import View

class Login(View):
    def get(self,request):
        return HttpResponse("GET 方法")

    def post(self,request):
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        if user == "runoob" and pwd == "123456":
            return HttpResponse("POST 方法")
        else:
            return HttpResponse("POST 方法 1")

CBV 体现了 Python 面向对象这一语言特性。CBV 是通过类的方式来编写视图函数。这相比较于 function,更能利用面向对象中多态的特性,因此更容易将项目中比较通用的功能抽象出来。CBV 的实现原理大家可以通过看 Django 的源码就进一步的理解,大概流程就是由 path 路由的 as_view() 创建一个类的实例由此关联到类视图,关联到类视图之后,通过 CBV 内部的 dispatch() 方法进行请求的分发处理,处理完成后并将 Response 返回。

注:当我们使用CBV方式时,首先要注意urls.py文件中要写成“类名.as_view()”方式映射,其次在类中我们定义的get/post方法这些方法的名字不是我们自己定义的,而是按照固定样式,View类中支持以下方法:

http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

当我们发送GET请求时,类自动将GET请求转到get方法去处理,其他请求同理!

注:

  • cbv定义类的时候必须要继承view;
  • 在写url的时候必须要加as_view;
  • 类里面使用form表单提交的话只有get和post方法;
  • 类里面使用ajax发送数据的话支持定义以下很多方法。

推荐文章

47条评论

  1. Really informative blog article. Thanks Again. Really Great. Tiffie Nathan Guenzi

  2. Hi there to all, the contents existing at this website are truly remarkable for people experience, well, keep up the good work fellows. Dorita Lock Alphonsine

  3. My spouse and I stumbled over here from a different page and thought I should check things out. Eleanora Zolly Dietrich

  4. This paragraph will help the internet users for setting up new website or even a blog from start to end.| Ciel Brennen Amalberga

  5. Takipçi satın almak için tıklayın. Hemen tıklayın ve
    takipçi satın al sayfamızdan takipçi satın alın.

  6. Why users still use to read news papers when in this technological world all is existing on web? Jobyna Felizio Heman

  7. Hello, I think your blog could possibly be having internet browser compatibility problems. Siouxie Grantham Lawford

  8. Thanks for your marvelous posting! I certainly enjoyed reading it, you may be a great author. I will make certain to bookmark your blog and definitely will come back from now on. I want to encourage yourself to continue your great posts, have a nice weekend! Neala Hew Deaner

  9. Awesome post. I am a regular visitor of your website and appreciate you taking the time to maintain the nice site. I will be a regular visitor for a long time. Dede Dukey Batchelor

  10. Thanks so much for the article post. Really looking forward to read more. Fantastic. Giulietta Wilmar Belshin

  11. Enjoyed every bit of your post. Much thanks again. Fantastic. Babita Prescott Petulah

  12. Great amazing things here. I am very happy to see your post. Thank you a lot and i am having a look forward to touch you. Will you please drop me a e-mail? Catie Franciskus Taro

  13. such a perfect means of writing? I ave a presentation subsequent week, and I am at the search for such information. Feel free to surf to my homepage; wellness blog Iormina Gaby Gerfen

  14. I truly appreciate this article post. Really looking forward to read more. Awesome. Twila Dennis Ferd

  15. Im obliged for the article. Really thank you! Cool. Miof Mela Bard Schick

  16. I really like your writing style, fantastic info , thanks for putting up : D. Brandise Giacomo Bushweller

  17. Oh my goodness! Incredible article dude! Many thanks, However I am experiencing issues with your RSS. Kirby Branden Elora

  18. Thanks for sharing your info. I really appreciate your efforts and I am waiting for your further post thank you once again. Murielle Brody Gayleen

  19. Some genuinely nice and useful information on this site, too I conceive the pattern holds wonderful features. Gretal Walton Gotthard

  20. When I initially left a comment I seem to have clicked the -Notify me when new comments are added- checkbox and now whenever a comment is added I get four emails with the same comment. Is there a way you are able to remove me from that service? Thank you! Allix Ennis Cyb

  21. Good post. I learn something totally new and challenging on sites I stumbleupon on a daily basis. It will always be useful to read articles from other authors and use a little something from their websites. Nettie West Geralda

  22. I was very pleased to find this site. I want to to thank you for your time for this particularly fantastic read!! I definitely loved every part of it and i also have you saved to fav to check out new stuff in your website. Loralee Arman Blakeley

  23. Very quickly this website will be famous among all
    blog viewers, due to it’s fastidious articles

  24. I every time used to read post in news papers but now as I am
    a user of internet thus from now I am using net for posts,
    thanks to web.

  25. Fabulous, what a website it is! This blog gives helpful facts to us, keep it up.

  26. Right here is the right site for anyone who wants to understand this topic.
    You know a whole lot its almost hard to argue with you (not that I personally will
    need to…HaHa). You definitely put a brand new spin on a topic
    that’s been written about for years. Excellent stuff, just wonderful!

  27. Thank you for sharing your info. I really appreciate
    your efforts and I will be waiting for your further post thanks once again.

  28. Heya terrific website! Does running a blog similar to this take a lot of work?
    I’ve very little understanding of coding but I was hoping to start
    my own blog soon. Anyway, if you have any ideas or tips
    for new blog owners please share. I know this is off topic nevertheless I just had to
    ask. Cheers!

  29. Hola! I’ve been reading your blog for a long time now
    and finally got the bravery to go ahead and give you a shout out from Lubbock Texas!
    Just wanted to say keep up the fantastic work!

  30. Wow, superb blog layout! How long have you been blogging for?

    you made blogging look easy. The overall look of your web site
    is magnificent, as well as the content!

  31. Pretty element of content. I simply stumbled upon your website and in accession capital to say that
    I get in fact loved account your blog posts. Any way I will be subscribing to your
    feeds or even I success you access consistently quickly.

    Here is my web page … CBD for dogs

  32. I don’t even know how I ended up here, but I thought this post was good.
    I do not know who you are but definitely you’re going to a famous blogger if you are not already 😉 Cheers!

  33. Hello! I simply wish to offer you a big thumbs up for the excellent information you have here on this post.
    I will be returning to your website for more soon.

  34. Simply desire to say your article is as surprising.

    The clarity for your post is just excellent and that
    i could assume you are a professional in this subject.
    Well together with your permission let me to seize your feed to stay up to date
    with drawing close post. Thanks one million and please keep
    up the enjoyable work.

  35. I’m really impressed with your writing skills as well as with the layout on your
    blog. Is this a paid theme or did you modify it yourself?
    Either way keep up the nice quality writing, it is rare
    to see a nice blog like this one nowadays.

  36. constantly i used to read smaller articles or reviews that also clear their motive, and that is
    also happening with this paragraph which I am reading here.

  37. I have to thank you for the efforts you have put in writing this site.

    I really hope to view the same high-grade blog posts from you in the future as well.

    In fact, your creative writing abilities has motivated me to get my
    own blog now 😉

    My page: cbd gummies

  38. Simply want to say your article is as astonishing. The clearness for
    your submit is simply nice and that i could assume you’re an expert in this subject.
    Fine along with your permission allow me to grasp your feed to keep up to date with drawing close
    post. Thank you 1,000,000 and please continue the gratifying work.

    my web site – cbd gummies

  39. I’m not sure why but this blog is loading very slow for me.
    Is anyone else having this problem or is it a issue on my end?
    I’ll check back later and see if the problem still exists.

  40. Valuable information. Fortunate me I discovered your site unintentionally, and I’m stunned why this
    twist of fate didn’t took place earlier! I bookmarked it.

  41. Actually no matter if someone doesn’t understand
    then its up to other visitors that they will help,
    so here it occurs.

  42. Hi there! This is kind of off topic but I need some guidance from an established blog.
    Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick.
    I’m thinking about setting up my own but I’m not sure where to start.
    Do you have any ideas or suggestions? Many thanks
    asmr 0mniartist

  43. Terrific work! This is the kind of information that
    should be shared around the internet. Disgrace on the search engines for now not positioning this submit
    upper! Come on over and talk over with my web site . Thank you
    =) asmr 0mniartist

  44. Greetings from Los angeles! I’m bored to
    tears at work so I decided to browse your website
    on my iphone during lunch break. I really like the information you
    present here and can’t wait to take a look when I get home.

    I’m surprised at how fast your blog loaded on my cell phone ..

    I’m not even using WIFI, just 3G .. Anyhow, very good blog!
    0mniartist asmr

  45. Keep on writing, great job! 0mniartist asmr

  46. I always spent my half an hour to read this weblog’s content everyday
    along with a cup of coffee. asmr 0mniartist

  47. Very nice post. I just stumbled upon your blog and wished to say that I’ve truly enjoyed surfing around
    your blog posts. After all I’ll be subscribing to
    your feed and I hope you write again soon!

    My web page … gold bee

发表评论

邮箱地址不会被公开。 必填项已用*标注