1.URL调度器示例
1.1 创建django项目结构
创建父级结构
django-admin startproject url_project
进入父级目录
cd url_project
python manage.py startapp url_app
1.2 路径转换器
str:匹配任何非空字符串,不包括路径分隔符’/'。如果转换器不包含在表达式中,这是默认值。
int:匹配零或任何正整数。返回一个int。
slug:匹配由ASCII字母或数字组成的字符串,以及横线和下划线字符。例如, building-your-1st-django_site可以匹配,django_@site是不可以匹配的。
uuid:匹配格式化的UUID。为防止多个URL映射到同一页面,必须包含破折号,并且字母必须是小写。例如,075194d3-6885-417e-a8a8-6c931e272f00。返回一个 UUID实例。
path:匹配任何非空字符串,包括路径分隔符 ‘/’,可以匹配完整的URL路径,而不仅仅是URL路径的一部分str,使用时要谨慎,因为可能造成后续的所有url匹配都失效。
1.3Django-URL调度器测试
在父级url
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('url_app/', include('url_app.urls'))
]
在子级url
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('articles/2003/',views.articles_2003),
path('articles/<int:year>/',views.articles_year),
path('articles/<int:year>/<int:month>', views.articles_year_month),
path('articles/<int:year>/<int:month>/<slug:slug>', views.articles_year_month_slug),
path('articles/<str:username>/',views.articles_str),
path('articles/<path:path>/',views.articles_path),
path('articles/<uuid:uuid>/',views.articles_uuid)
]
在子级view
from django.shortcuts import render, HttpResponse
# Create your views here.
def articles_2003(request):
return HttpResponse('articles_2003')
def articles_year(request, year):
return HttpResponse(f'articles_year.year{year}')
def articles_year_month(request, year, month):
return HttpResponse(f'articles_year.year{year},{month}')
def articles_year_month_slug(request, year, month, slug):
return HttpResponse(f'articles_year.year{year},{month},{slug}')
def articles_str(request,username):
return HttpResponse(f'articles_str,username:{username}')
def articles_path(request,path):
return HttpResponse(f'articles_str,path:{path}')
def articles_uuid(request,uuid):
return HttpResponse(f'articles_str,uuid:{uuid}')
1.4 URL调度器总结
从URL中捕获值,请使用尖括号
捕获的值可以选择包含转换器类型。例如,用于 int:name捕获,前面的int指整数参数,name是参数的名称
没有必要添加一个前导斜杠,因为每个URL都有,例如,使用articles而不是/articles。
示例请求说明:
/articles/2005/03/ 匹配列表中的第三个条目。Django会调用这个函数,views.month_archive(request, year=2005, month=3)
/articles/2003/ 会匹配列表中的第一个模式,而不是第二个模式,因为模式是按顺序测试的,而第一个模式是第一个要传递的测试。看看利用匹配顺序插入像这样的特殊情况。在这里,Django会调用这个函数 views.special_case_2003(request)
/articles/2003 不匹配任何这些模式,因为每种模式都要求URL以斜线结尾,不过在浏览器访问时,会自动添加 / 。
**/articles/2003/03/building-a-django-site/ **将匹配最终模式。Django会调用这个函数 。views.article_detail(request, year=2003, month=3, slug=“building-a-django-site”)
2. 自定义路径转换器
2.1 方法概述
转换器是需要包含以下内容的类:
- 应该regex类属性,作为应该re匹配字符串
- to_python(self,value)方法,它处理的匹配字符串转换要传递到视图函数的类型
- to_url(self, value)方法, 用于处理将python类型转换为URL中使用的字符串
2.2 测试
创建converters.py文件编写规则
class MyYearConverter(object):
regex = '[0-9]{4}'
def to_python(self, value):
return int(value)
def to_url(self, value):
return '%04d' % value
注册并使用规则
from django.contrib import admin
from django.urls import path
from . import views
# 注册自定义路径转换器
from . import converters
from django.urls import register_converter
register_converter(converters.MyYearConverter, 'yyyy')
urlpatterns = [
path('atricles/<yyyy:year>/',views.articles_year)
]
3.URL调度器中正则表达式的使用
3.1方法概述
使用正则表达式匹配路径,请使用 re_path()而不是path()
在Python正则表达式中,命名正则表达式组的语法是(?Ppattern),其中name是组的名称,并且 pattern是一些要匹配的模式
3.2测试
url地址
from django.contrib import admin
from django.urls import path,re_path
from . import views
urlpatterns = [
re_path(r'^articles/(?P<year>[0-9]{4})/$', views.articles_year), # 4位数字
re_path('^articles/(?P<year>\d+/$)', views.articles_year), #任意个数字
re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.articles_year_month) # 年份4位,月份2为
re_path(r'^comments/(?:page-(?P<page_number>\d+)/)?$', views.comments) # page-加一个数字,嵌套正则
]
view视图
from django.shortcuts import render, HttpResponse
# Create your views here.
def articles_2003(request):
return HttpResponse('articles_2003')
def articles_year(request, year):
return HttpResponse(f'articles_year.year{year}')
def articles_year_month(request, year, month):
return HttpResponse(f'articles_year.year{year},{month}')
def comments(request, page_number):
return HttpResponse(f'comments:{page_number}')
4.默认值使用
4.1方法概述
当我们在查询数据时,就可以使用一个默认值,当用户未在指定url地址(页数)就默认为第1页
4.2测试
url地址
from django.contrib import admin
from django.urls import path,re_path
from . import views
urlpatterns = [
# 使用默认值
path('blog/',views.do_page),
path('blog/<int:num>/',views.do_page)
]
view视图
from django.shortcuts import render, HttpResponse
def do_page(request, num=1):
return HttpResponse(f'page={num}')
5.url异常处理
5.1概述
handler400- 状态码400
handler403- 状态码403
handler404- 状态码404
handler500- 状态码500
当我们的状态码为某个值时,做出相应的反馈
5.2 测试
当我们找不到路由时,返回一个视图
- 在 settings中修改配置:
DEBUG = False
ALLOWED_HOSTS = ['*', ]
- 在主应用的urls中配置:
import url_app
# 异常处理
handler404 = "url_app.views.page_not_found"
- 在polls应用(子应用)的views中添加函数page_not_found:
from django.shortcuts import render, HttpResponse
#handler404 处理函数
def page_not_found(request, exception):
return HttpResponse('404出现异常')
- 浏览器测试访问,找不到匹配的路由
6.引用其它URL调度器
- 多个 patterns
from django.contrib import admin
from django.urls import path,re_path,include
from . import views
morenzhi_patterns = [
path('blog/',views.do_page),
path('blog/<int:num>/',views.do_page)
]
urlpatterns = [
# 1.使用其他include包含其他patterns
path('', include(morenzhi_patterns))
]
- 使用include消除重复前缀
from django.contrib import admin
from django.urls import path,re_path,include
from . import views
urlpatterns = [
# 2.使用include消除重复前缀
path('articles/',include([
path('articles/2003/',views.articles_2003),
path('articles/<int:year>/',views.articles_year),
]))
]
- 传递捕获的参数
在主urls中配置:
from django.contrib import admin
from django.urls import path, include
import poll_app
import url_app
urlpatterns = [
path('<usernameapp>/',include("poll_app.urls"))
]
对应的 polls 应用下的urls中配置:
from django.urls import path
from . import views
urlpatterns = [
path('arg_test/', views.arg_usernameapp_test)
]
对应的 polls 应用下的views中编写函数:
from django.shortcuts import render, HttpResponse
# Create your views here.
def arg_usernameapp_test(request,usernameapp):
return HttpResponse(f'<usernameapp>:{usernameapp}')
7.额外的参数
url地址
from django.urls import path
from . import views
urlpatterns = [
path('arg_test/', views.arg_usernameapp_test),
path('param_test/', views.param_test, {'user':'root','password':'1234'})
]
views视图
from django.shortcuts import render, HttpResponse
def param_test(request, usernameapp, user, password):
return HttpResponse(f'user:{user}, password:{password}')
8.URL反向解析(重定向)
8.1 概述
url调度器除了从用户发起请求,到匹配对应的view,还能在python程序中调用进行匹配,通过 path或re_path 中 的name属性进行解析
在模板中,使用url模板标签
在Python代码中(主要是views),使用 reverse() 函数
在模型实例中,使用 get_absolute_url() 方法
8.2 在视图中重定向url
views视图中
from django.shortcuts import render, HttpResponse,HttpResponseRedirect
from django.urls import reverse
# Create your views here.
def first_request(request):
# return HttpResponse('first_request')
return HttpResponseRedirect(reverse('news-year-archive',args=(22,)))
def year_archive(request, year):
return HttpResponse(f'重定向成功year:{year}')
url中:
from django.urls import path
from . import views
urlpatterns = [
path('first_request_url/', views.first_request),
path('articles/<int:year>/', views.year_archive, name='news-year-archive'),
]
8.3在模板中测试
在views.py中
from django.urls import path
from . import views
urlpatterns = [
path('first_request_url/', views.first_request),
path('articles/<int:year>/', views.year_archive, name='news-year-archive'),
path('do_html/', views.do_html)
]
在url路由中
from django.shortcuts import render, HttpResponse,HttpResponseRedirect
from django.urls import reverse
# Create your views here.
def first_request(request):
# return HttpResponse('first_request')
return HttpResponseRedirect(reverse('news-year-archive',args=(22,)))
def year_archive(request, year):
return HttpResponse(f'重定向成功year:{year}')
def do_html(request):
return render(request, 'redirect_test.html')
templates模板中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="{% url 'news-year-archive' 2004 %}">url反向解析</a>
</body>
</html>
9.命名控件——解决重定向名称错乱
9.1概述
主要用于配合url反向解析 使用,多个不同的urls文件中可能配置同名的 name,那么为了进行区分,给不同的urls进行不同的命名,切记同一个项目下命名空间不能重复!
9.2 测试
urls.py中
from django.urls import path
from . import views
app_name = 'reverse'
urlpatterns = [
path('first_request_url/', views.first_request),
path('articles/<int:year>/', views.year_archive, name='news-year-archive'),
path('do_html/', views.do_html)
]
views.py
from django.shortcuts import render, HttpResponse,HttpResponseRedirect
from django.urls import reverse
# Create your views here.
def first_request(request):
# return HttpResponse('first_request')
return HttpResponseRedirect(reverse('reverse:news-year-archive',args=(22,)))
def year_archive(request, year):
return HttpResponse(f'重定向成功year:{year}')
def do_html(request):
return render(request, 'redirect_test.html')
template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="{% url 'reverse:news-year-archive' 2004 %}">url反向解析</a>
</body>
</html>