Diango路由映射FBV和CBV

本文介绍了Django框架中的两种请求处理方式:FBV(函数式视图)和CBV(类视图),详细解释了它们的区别及实现方法,并提供具体的代码示例。

django中请求处理方式有2种:FBV(function base views) 和 CBV(class base views),换言之就是一种用函数处理请求,一种用类处理请求。

FBV

# url.py
from django.conf.urls import url, include
from mytest import views
 
urlpatterns = [
    url(r‘^index/‘, views.index),
]

# views.py
from django.shortcuts import render
 
 
def index(req):
    if req.method == ‘POST‘:
        print(‘method is :‘ + req.method)
    elif req.method == ‘GET‘:
        print(‘method is :‘ + req.method)
    return render(req, ‘index.html‘)

 

CBV

# urls.py
from mytest import views
 
urlpatterns = [
    # url(r‘^index/‘, views.index),
    url(r‘^index/‘, views.Index.as_view()),
]

# views.py
from django.views import View

 
class Index(View):
    def get(self, req):
        print(‘method is :‘ + req.method)
        return render(req, ‘index.html‘)
 
    def post(self, req):
        print(‘method is :‘ + req.method)
        return render(req, ‘index.html‘)

# 注:类要继承 View ,类中函数名必须小写。
# cbv 模式下继承了django的view类
# 在请求来临的时候,会调用继承类的 dispatch 方法
# 通过反射的方法它会去调用自己写的视图函数, 那么这便是一个切入点,可以在自己的 cbv 视图中,重写这个方法。 
class View(object):

    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)
CBV模式下的一个拓展

 

转载于:https://www.cnblogs.com/huangjm263/p/8781621.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值