Django之路由配置
1、路由配置-path
- path()函数
- 导入:from django.urls import path
- 语法:path(route,views,name=None)
- 参数:
1.route:字符串类型,匹配的请求路径 2.views:指定路径所对应的视图处理函数的名称 3.name:为地址起别名,在模板中地址反向解析时使用 - urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index_page),
path('page/1',views.page_1_views),
path('page/2',views.page_2_views)
]
from django.http import HttpResponse
def index_page(resquest):
h = "<h1>这是我的首页</h1>"
return HttpResponse(h)
def page_1_views(resquest):
h = "<h1>这是编号1的网页</h1>"
return HttpResponse(h)
def page_2_views(resquest):
h = "<h1>这是编号2的网页</h1>"
return HttpResponse(h)
2、路由转换器-path()
- 语法:<转换器类型:自定义名称>
- 作用:若转换器类型匹配到对应类型的数据,则将数据按照关键字传参的方式传递给视图函数。
- 示例:
path('page/<int:pg>',views.xxx)
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('page/<int:pg>',views.page_views)
]
from django.http import HttpResponse
def page_views(resquest,pg):
h = "<h1>这是编号%s的网页!</h1>"%(pg)
return HttpResponse(h)
转换器类型 | 作用 | 示例 |
---|
str | 匹配除了“/”之外的非空字符串 | “v1/users/< str:username >” 匹配 /v1/users/ane | int | 匹配0或任何正整数,返回一个int | “page/< int:pg >” 匹配 /page/10 | slug | 匹配任意由ASCII字母或数字以及连字符和下划线组成的短标签 | “detail/< slug:sl >” 匹配 detail/this-is-django | path | 匹配非空字段,包括路径分隔符“/” | “v1/users/< path:ph >” 匹配 /v1/users/a/b/c |
- 练习:制作一个小计算器
浏览器输入:http://127.0.0.1:8000/100/add/200 页面显示结果:300 urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('<int:n>/<str:op>/<int:m>',views.cal_view)
]
views.py
from django.http import HttpResponse
def cal_view(request,n,op,m):
if op not in("add","sub","mul"):
return HttpResponse("Your op is wrong")
result = 0
if op == "add":
result = n + m
elif op == "sub":
result = n - m
elif op == "mul":
result = n * m
return HttpResponse('结果为:%s'%(result))
3、路由转换器-re_path()
- re_path()函数在url的匹配过程中可以使用正则表达式进行精确匹配。
- 语法:re_path(reg,view,name=xxx)
正则表达式为命名分组模式(?Ppattern);匹配提取参数后用关键字传参方式传递给视图函数。
re_path(r'^(?P<x>\d{1,2})/(?P<op>\w+)/(?P<y>\d{1,2})$',views.cal_view)
- 练习
访问地址:http://127.0.0.1:8000/birthday/四位数字/一到两位数字/一到两位数字 http://127.0.0.1:8000/birthday/四位数字/一到两位数字/一到两位数字 最终输出:生日为:xxxx年xx月xx日
urls.py
from django.contrib import admin
from django.urls import path, re_path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^birthday/((?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<year>\d{4}))$',views.birthday_view),
re_path(r'^birthday/(?P<year>\d{4})/((?P<month>\d{1,2})/(?P<day>\d{1,2}))$',views.birthday_view)
]
views.py
from django.http import HttpResponse
def birthday_view(request,year,month,day):
bd = "生日为:%s年%s月%s日"%(year,month,day)
return HttpResponse(bd)
|