Python Web框架——Django学习的第三天

Python Web框架——Django学习的第三天

一:对第二天的所学内容的复习和深化

1.path转换器的使用
在这里插入图片描述

注意:注意:注意:在urls.py文件中的路由,通过游览器寻找路由是类似于一个数组的寻找方式,从上至下

  • 运用path转换器
  • 语法:<转换器类型:自定义名>
  • 作用:若转换器类型匹配到对应类型的数据,则将数据按照关键则传参的方式传递给视图函数
  • 例子:path(‘page/int:page’,views.xxx)

在这里插入图片描述
urls.py文件中的代码:

from django.contrib import admin
from django.urls import path,re_path
from app01 import views

urlpatterns = [
   #path转换器
   path('page/<int:pg>',views.paggen_view),

]

views.py文件中的代码:

form django.shortcuts import render,HttpResponse
def pageen_view(request,pg):
      html = '这是编号为%s的网页'%(pg)
      return HttpResponse(html)

练习:小计算器
在这里插入图片描述
urls代码:

from django.contrib import admin
from django.urls import path,re_path
from app01 import views

urlpatterns = [
   #path转换器
   path('<int:number>/<str:op>/<int:number2>',views.calculate),
]

views.py代码

from django.shortcuts import render,HttpResponse
def calculate(request,number,op,number2):
    if op not in ['add','sub','mul']:
        return HttpResponse("Ypur op is wrong")
    if op =='add':
        result = number +number2
    elif op== 'sub':
        result = number-number2;
    elif op =='mul':
        result =number *number2;
    return HttpResponse('计算结果为%s'%(result))

2.re_path()函数讲解

  • re_path()函数
  • 在url的匹配过程中可以使用正则表达式进行精确匹配
  • 语法:
    -
    注意格式:

样例:

猜你喜欢

转载自blog.csdn.net/qq_51269815/article/details/121767400