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

视图

负责接收请求和返回响应

FBV和CBV

  • FBV

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

    1 from django.conf.urls import url
    2 from django.contrib import admin
    3 
    4 from test_app import views
    5 urlpatterns = [
    6     url(r'^test/', views.test),
    7 ]
    /[project name]/urls.py
    1 from django.shortcuts import render
    2 
    3 
    4 def test(request):
    5     if (request.method == 'POST'):
    6         ...  # do something
    7     else:
    8         ...  # do something
    /[app name]/views.py
  • CBV

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

    1 from django.conf.urls import url
    2 from django.contrib import admin
    3 
    4 from test_app import views
    5 urlpatterns = [
    6     url(r'^test/', views.Test.as_view()),
    7 ]
    /[project name]/urls.py
     1 from django.shortcuts import render
     2 from django.views import View
     3 
     4 
     5 class Test(View):
     6     def get(self, request):
     7         ... # do something
     8 
     9     def post(self, request):
    10         ... # 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=[别名]), ]

分组匹配

  • 位置匹配

    1 from django.conf.urls import url
    2 
    3 from test_app import views
    4 urlpatterns = [
    5     url(r'^test/([a-zA-z]+)/([0-9]{1,2})', views.Test.as_view()),
    6 ]
    /[project name]/urls.py
    1 from django.shortcuts import render, HttpResponse
    2 from django.views import View
    3 
    4 
    5 class Test(View):
    6     def get(self, request, name, age):
    7         resp_str = '姓名:{} 年龄:{}'.format(name,age)
    8         return HttpResponse(resp_str)
    /[app name]/views.py
    result
  • 命名匹配

    1 from django.conf.urls import url
    2 
    3 from test_app import views
    4 urlpatterns = [
    5     url(r'^test/(?P<name>[a-zA-z]+)/(?P<age>[0-9]{1,2})/', views.Test.as_view()),
    6 ]
    /[project name]/urls.py
    1 from django.shortcuts import render, HttpResponse
    2 from django.views import View
    3 
    4 
    5 class Test(View):
    6     def get(self, request, age, name):
    7         resp_str = '姓名:{} 年龄:{}'.format(name,age)
    8         return HttpResponse(resp_str)
    /[app name]/views.py
    result

include

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

1 from django.conf.urls import url,include
2 
3 urlpatterns = [
4     url(r'^test_app/',include('test_app.urls'))
5 ]
/[project name]/urls.py
1 from django.conf.urls import url, include
2 
3 from . import views
4 
5 urlpatterns = [
6     url(r'^test', views.Test.as_view())
7 ]
/[app name]/urls.py

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

URL命名&反向解析

1 from django.conf.urls import url
2 from test_app import views
3 
4 
5 urlpatterns = [
6     url(r'^test/([a-zA-Z]+)/([0-9]{1,2})', views.Test.as_view(), name='test_name')
7 ]
/[project name]/urls.py
 1 from django.shortcuts import render
 2 from django.views import View
 3 from django.urls import reverse
 4 
 5 
 6 class Test(View):
 7     def get(self, request, name, age):
 8         request_url = reverse('test_name',args=(name,age))
 9         reverse_url = reverse('test_name',args=('zhangsan',20))
10         return render(request, 'test.html', {'request_url':request_url,'reverse_url': reverse_url})
/[app name]/views.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>test</title>
 6 </head>
 7 <body>
 8 请求的URL:
 9 <br>
10 {{ request_url }}
11 <hr>
12 视图中解析:<br>
13 {{ reverse_url }}
14 <hr>
15 模板中解析:<br>
16 {% url 'test_name' 'zhangsan' 19 %}
17 </body>
18 </html>
/templates/test.html
result

补充

APPEND_SLASH

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

给视图传递额外参数

1 from django.conf.urls import url
2 from test_app import views
3 
4 urlpatterns = [
5     url(r'^test/([a-zA-Z]+)/([0-9]{1,2})', views.Test.as_view(), {'sex': 'male'})
6 ]
/[project name]/urls.py
1 from django.shortcuts import render, HttpResponse
2 from django.views import View
3 
4 
5 class Test(View):
6     def get(self, request, age, name,sex):
7         resp_str = '姓名:{} 年龄:{} 性别:{}'.format(name,age,sex)
8         return HttpResponse(resp_str)
/[app name]/views.py
result

路由中的namespace

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

1 from django.conf.urls import url, include
2 from test_app import views
3 
4 urlpatterns = [
5     url(r'^test/',views.Test.as_view()),
6     url(r'^test_app1/', include('test_app1.urls', namespace='app1')),
7     url(r'^test_app2/', include('test_app2.urls', namespace='app2')),
8 ]
/django_test/urls.py
 1 from django.shortcuts import render
 2 from django.views import View
 3 from django.urls import reverse
 4 
 5 
 6 class Test(View):
 7     def get(self, request):
 8         app1_url = reverse('app1:same_name', args=('zhangsan', 19))
 9         app2_url = reverse('app2:same_name', args=('lisi', 20))
10         return render(request, 'test.html', {'app1_url': app1_url, 'app2_url': app2_url})
/test_app/views.py
1 from django.conf.urls import url, include
2 
3 from . import views
4 
5 urlpatterns = [
6     url(r'^test/([a-zA-Z]+)/([0-9]{1,2})', views.Test.as_view(), name='same_name')
7 ]
/test_app1/urls.py
1 from django.conf.urls import url, include
2 
3 from . import views
4 
5 urlpatterns = [
6     url(r'^test/([a-zA-Z]+)/([0-9]{1,2})', views.Test.as_view(), name='same_name')
7 ]
/test_app2/urls.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>test</title>
 6 </head>
 7 <body>
 8 视图中使用
 9 <br>
10 {{ app1_url }}
11 <br>
12 {{ app2_url }}
13 <hr>
14 模板中使用
15 <br>
16 {% url 'app1:same_name' 'zhangsan' 19%}
17 <br>
18 {% url 'app2:same_name' 'lisi' 20 %}
19 </body>
20 </html>
/templates/test.html
result

路由分发

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

1 from django.conf.urls import url
2 from img_upload import views
3 
4 urlpatterns = [
5     url(r'^user/', [(
6         url(r'^add/', views.add),  # host:port/user/add/
7         url(r'^list/', views.list)  # host:port/user/list/
8     ), None, None]),
9 ]
/django_test/urls.py
posted @ 2018-04-29 16:50  zze  阅读(282)  评论(0编辑  收藏  举报