python框架之Django(4)-视图&路由

视图

负责接收请求和返回响应

FBV和CBV

  • FBV

    FBV(function base views) 就是在视图里使用函数处理请求。

     from django.conf.urls import url
    from django.contrib import admin from test_app import views
    urlpatterns = [
    url(r'^test/', views.test),
    ]

    /[project name]/urls.py

     from django.shortcuts import render
    
     def test(request):
    if (request.method == 'POST'):
    ... # do something
    else:
    ... # do something

    /[app name]/views.py

  • CBV

    CBV(class base views) 就是在视图里使用类处理请求。

     from django.conf.urls import url
    from django.contrib import admin from test_app import views
    urlpatterns = [
    url(r'^test/', views.Test.as_view()),
    ]

    /[project name]/urls.py

     from django.shortcuts import render
    from django.views import View class Test(View):
    def get(self, request):
    ... # do something def post(self, request):
    ... # do something

    /[app name]/views.py

request

1. request.method    # 获取请求的方法(GET、POST等)
2. request.GET # 通常用来获取URL里面的参数
3. request.POST # 用来获取POST提交过来的数据
4. request.path_info # 获取用户请求的路径(不包含IP和端口和URL参数)
5. request.body # 获取请求正文

response

1. HttpResponse        # 返回字符串内容
2. render # 渲染并返回html页面
3. redirect # 返回一个重定向
4. JsonResponse # 将对象序列化成Json格式字符串并返回

路由

格式

from django.conf.urls import url

urlpatterns = [
url([正则], [视图函数],[参数],name=[别名]),
] # 注意:Django 2.0中有所不同,如下:
from django.urls import path urlpatterns = [
path([正则], [视图函数],[参数],name=[别名]),
]

分组匹配

  • 位置匹配

     from django.conf.urls import url
    
     from test_app import views
    urlpatterns = [
    url(r'^test/([a-zA-z]+)/([0-9]{1,2})', views.Test.as_view()),
    ]

    /[project name]/urls.py

     from django.shortcuts import render, HttpResponse
    from django.views import View class Test(View):
    def get(self, request, name, age):
    resp_str = '姓名:{} 年龄:{}'.format(name,age)
    return HttpResponse(resp_str)

    /[app name]/views.py

    python框架之Django(4)-视图&路由

    result

  • 命名匹配

     from django.conf.urls import url
    
     from test_app import views
    urlpatterns = [
    url(r'^test/(?P<name>[a-zA-z]+)/(?P<age>[0-9]{1,2})/', views.Test.as_view()),
    ]

    /[project name]/urls.py

     from django.shortcuts import render, HttpResponse
    from django.views import View class Test(View):
    def get(self, request, age, name):
    resp_str = '姓名:{} 年龄:{}'.format(name,age)
    return HttpResponse(resp_str)

    /[app name]/views.py

    python框架之Django(4)-视图&路由

    result

include

可以让路由信息保存在多个文件中

 from django.conf.urls import url,include

 urlpatterns = [
url(r'^test_app/',include('test_app.urls'))
]

/[project name]/urls.py

 from django.conf.urls import url, include

 from . import views

 urlpatterns = [
url(r'^test', views.Test.as_view())
]

/[app name]/urls.py

上述配置对应的地址就是: http://localhost:8000/test_app/test

URL命名&反向解析

 from django.conf.urls import url
from test_app import views urlpatterns = [
url(r'^test/([a-zA-Z]+)/([0-9]{1,2})', views.Test.as_view(), name='test_name')
]

/[project name]/urls.py

 from django.shortcuts import render
from django.views import View
from django.urls import reverse class Test(View):
def get(self, request, name, age):
request_url = reverse('test_name',args=(name,age))
reverse_url = reverse('test_name',args=('zhangsan',20))
return render(request, 'test.html', {'request_url':request_url,'reverse_url': reverse_url})

/[app name]/views.py

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
请求的URL:
<br>
{{ request_url }}
<hr>
视图中解析:<br>
{{ reverse_url }}
<hr>
模板中解析:<br>
{% url 'test_name' 'zhangsan' 19 %}
</body>
</html>

/templates/test.html

python框架之Django(4)-视图&路由

result

补充

APPEND_SLASH

settings.py配置文件中默认没有 APPEND_SLASH这个项,但Django默认这个参数为 APPEND_SLASH = True。 作用就是自动在网址结尾加'/'。(测试不生效注意清理历史缓存)

给视图传递额外参数

 from django.conf.urls import url
from test_app import views urlpatterns = [
url(r'^test/([a-zA-Z]+)/([0-9]{1,2})', views.Test.as_view(), {'sex': 'male'})
]

/[project name]/urls.py

 from django.shortcuts import render, HttpResponse
from django.views import View class Test(View):
def get(self, request, age, name,sex):
resp_str = '姓名:{} 年龄:{} 性别:{}'.format(name,age,sex)
return HttpResponse(resp_str)

/[app name]/views.py

python框架之Django(4)-视图&路由

result

路由中的namespace

用于区分多个app中name相同的url

 from django.conf.urls import url, include
from test_app import views urlpatterns = [
url(r'^test/',views.Test.as_view()),
url(r'^test_app1/', include('test_app1.urls', namespace='app1')),
url(r'^test_app2/', include('test_app2.urls', namespace='app2')),
]

/django_test/urls.py

 from django.shortcuts import render
from django.views import View
from django.urls import reverse class Test(View):
def get(self, request):
app1_url = reverse('app1:same_name', args=('zhangsan', 19))
app2_url = reverse('app2:same_name', args=('lisi', 20))
return render(request, 'test.html', {'app1_url': app1_url, 'app2_url': app2_url})

/test_app/views.py

 from django.conf.urls import url, include

 from . import views

 urlpatterns = [
url(r'^test/([a-zA-Z]+)/([0-9]{1,2})', views.Test.as_view(), name='same_name')
]

/test_app1/urls.py

 from django.conf.urls import url, include

 from . import views

 urlpatterns = [
url(r'^test/([a-zA-Z]+)/([0-9]{1,2})', views.Test.as_view(), name='same_name')
]

/test_app2/urls.py

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
视图中使用
<br>
{{ app1_url }}
<br>
{{ app2_url }}
<hr>
模板中使用
<br>
{% url 'app1:same_name' 'zhangsan' 19%}
<br>
{% url 'app2:same_name' 'lisi' 20 %}
</body>
</html>

/templates/test.html

python框架之Django(4)-视图&路由

result

路由分发

路由可以以以下格式多级分发:

 from django.conf.urls import url
from img_upload import views urlpatterns = [
url(r'^user/', [(
url(r'^add/', views.add), # host:port/user/add/
url(r'^list/', views.list) # host:port/user/list/
), None, None]),
]

/django_test/urls.py

上一篇:Javascript 布尔操作符总结


下一篇:Leetcode 863. 二叉树中所有距离为 K 的结点