2Django路由配置(python3.10+Django3.29)

当用户浏览器请求的时候,django会首先访问settings.py文件里的主路由“ROOT_URLCONF”配置列表中的urlpatterns变量,这个变量是一个数组,数组里面有很多path函数,在这个path函数中我们会配置各种各样的路由以及和路由绑定的视图函数名称

练习1:

访问127.0.0.1:8000,在网页中输出这是我的首页

访问127.0.0.1:8000/page/1,在网页中输出这是编号为1的网页

URL:

from django.urls import path
from . import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index_view),
    path('page/1',views.page1_view)

VIEWS:

from django.http import HttpResponse
def index_view(request):
    html="<h1>这是我的首页</h1>"
    return HttpResponse(html)

def page1_view(request):
    html="这是编号为1的网页"
    return HttpResponse(html)

 path转换器:

语法:<转换器类型:自定义名称>

作用:若转换器类型匹配到对应类型的数据,则将数据按照关键字传参的方式传递给视图函数

转换器类型:str,int,slug,path

转换器类型 作用 样例
str 匹配除了'/'之外的非空字符串 /v1/users/<str:zhangsan>
int 匹配9或任何整数返回一个int /page/<int:page>
slug 匹配任意ascii字母数字下划线及连字符组成的段标签 /detail/<slug:sl>
path 匹配非空字段,包括路径分隔符"/" /v1/users/<path:ph>

 练习2:

使用path转换器配置路由,当我输入1就提示你访问的是1,当我输入的是2网页就提示2

URL:

from django.urls import path
from . import views
urlpatterns = [
    path('admin/', admin.site.urls),
    #http://127.0.0.1:8000/page/3-100
    path('page/<int:pg>',views.pagen_view),
]

VIEWS:

def pagen_view(request,pg):
    html="这是编号为%s的网页!"%(pg)
    return HttpResponse(html)

 练习3

制作一个小计算器实现加减乘除,页面显示结果。例如加法:127.0.0.1:8000/99/add/100

URL:

path('<int:n>/<str:op>/<int:m>',views.cal_view),

VIEWS:

#加减乘除
def cal_view(request,n,op,m):
    if op not in ['add','sub','mul','chu']:
        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
    else:
        result = n / m
    return HttpResponse('结果为:%s'%(result))

 path路由的升级版re_path()可用于正则表达式精确匹配

语法:re_path(reg,view,name=xxx)

注意事项:正则表达式为命名分组模式(?P<name>pattern)

练习4:

制作一个小计算器实现加减乘除,页面显示结果。例如加法:127.0.0.1:8000/99/add/10

要求只能做两位数的运算

\d:表示整数

\d{1,2}:表示1到2位的整数

(?P<x>\d{1,2}):组名x,正则是匹配1-2位的整数

\w:表示字符

\w+:表示多个字符

(?P<op>\w+):组名op,正则是匹配多个字符

练习4

匹配两位整数的加减程序运算

URL:

re_path(r'^(?P<x>\d{1,2})/(?P<op>\w+)/(?P<y>\d{1,2})$', views.cal2_view)

VIEWS:

def cal2_view(request,x,op,y):
    if op not in ['add','sub','mul','chu']:
        return HttpResponse('Your op is wrong')
    if op == "add":
        result = int(x) + int(y)
    elif op == "sub":
        result = int(x) - int(y)
    elif op == "mul":
        result = int(x) * int(y)
    else:
        result = int(x) / int(y)
    return HttpResponse('结果为:%s'%(result))

 练习5:

127.0.0.1:8000/birthday/四位数字/一到两位数字/一到两位数字

127.0.0.1:8000/birthday/一到两位数字/一到两位数字/四位数字

URL:

re_path(r'^birthday/(?P<x>\d{4})/(?P<y>\d{1,2})/(?P<z>\d{1,2})$',views.birthday_view),
re_path(r'^birthday/(?P<y>\d{1,2})\d{1,2}/(?P<z>\d{1,2)/(?P<x>\d{4})$',views.birthday_view),

VIEWS:

def birthday_view(request,x,y,z):
    html = '生日为%s年%s月%s日'%(x,y,z)
    return HttpResponse(html)

 

posted @ 2021-11-24 14:28  linuxTang  阅读(194)  评论(0)    收藏  举报