标签:alt inf 两种 pac space 继承 代码 color http
django中请求处理方式有2种:FBV 和 CBV
FBV(function base views) 就是在视图里使用函数处理请求。
看代码:
urls.py
| 1 2 3 4 5 6 7 8 | fromdjango.conf.urls importurl, include# from django.contrib import adminfrommytest importviewsurlpatterns =[    # url(r‘^admin/‘, admin.site.urls),    url(r‘^index/‘, views.index),] | 
views.py
| 1 2 3 4 5 6 7 8 9 | fromdjango.shortcuts importrenderdefindex(req):    ifreq.method ==‘POST‘:        print(‘method is:‘ +req.method)    elifreq.method ==‘GET‘:        print(‘method is:‘ +req.method)    returnrender(req, ‘index.html‘) | 
注意此处定义的是函数【def index(req):】
index.html
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>index</title></head><body>    <form action="" method="post">        <inputtype="text"name="A"/>        <inputtype="submit"name="b"value="提交"/>    </form></body></html> | 
上面就是FBV的使用。
CBV(class base views) 就是在视图里使用类处理请求。
将上述代码中的urls.py 修改为如下:
| 1 2 3 4 5 6 | frommytest importviewsurlpatterns =[    # url(r‘^index/‘, views.index),    url(r‘^index/‘, views.Index.as_view()),] | 
注:url(r‘^index/‘, views.Index.as_view()), 是固定用法。
将上述代码中的views.py 修改为如下:
| 1 2 3 4 5 6 7 8 9 10 11 | fromdjango.views importViewclassIndex(View):    defget(self, req):        print(‘method is:‘ +req.method)        returnrender(req, ‘index.html‘)    defpost(self, req):        print(‘method is:‘ +req.method)        returnrender(req, ‘index.html‘) | 
注:类要继承 View ,类中函数名必须小写。
两种方式没有优劣,都可以使用。
标签:alt inf 两种 pac space 继承 代码 color http
原文地址:https://www.cnblogs.com/ExMan/p/9869998.html