Django 用re_path()方法正则匹配复杂路由

app1.url.py

复制代码
from django.urls import path, re_path
from . import views

urlpatterns = [
    path('index', views.index, name='index'),
    path('test', views.test, name='test'),
    path('test_int/<int:id>/', views.test_int, name='test_int'),
    path('test_str/<str:strdata>/', views.test_str, name='test_str'),
    path('test_slug/<slug:slugdata>/', views.test_slug, name='test_slug'),
    path('book_uuid/<uuid:bookuuid>/', views.book_uuid, name='book_uuid'),
    re_path(r'article_list/(?P<year>\d{4})/', views.article_list, name='article_list'),     # 用re_path()方法正则匹配复杂路由
    re_path(r'article_page/(?P<page>\d+)&key=(?P<key>\w+)', views.article_page, name='article_page'),     # 用re_path()方法正则匹配复杂路由
]

app1.views.py

复制代码
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
    return HttpResponse("app1 的index")

def test(request):
    return render(request, '1/index.html', {})

def test_int(request, id):
    # 你可以在这里使用 'id',比如从数据库获取对应的数据
    # ...
    response = HttpResponse(f"test_int路由访问参数:{id}")
    response['Content-Type'] = "text/html; charset=utf-8"
    return response

def test_str(request, strdata):
    # 你可以在这里使用 'id',比如从数据库获取对应的数据
    # ...
    response = HttpResponse(f"test_str路由访问参数:{strdata}")
    response['Content-Type'] = "text/html; charset=utf-8"
    return response

def test_slug(request, slugdata):
    # 你可以在这里使用 'id',比如从数据库获取对应的数据
    # ...
    response = HttpResponse(f"test_slug路由访问参数:{slugdata}")
    response['Content-Type'] = "text/html; charset=utf-8"
    return response

from uuid import UUID

def book_uuid(request, bookuuid: UUID):
    # 在这里,'bookuuid' 是一个UUID 对象。
    return HttpResponse(f"Book's UUID is: {str(bookuuid)}")


# 用re_path()方法正则匹配复杂路由
def article_list(request, year):
    return HttpResponse(f"文章列表年份是:{year}")


# 用re_path()方法正则匹配复杂路由
def article_page(request, page, key):
    return HttpResponse(f"文章页数是:{page},{key}")
相关推荐
凯瑟琳.奥古斯特1 天前
Django Flask FastAPI 三者对比
开发语言·python·django·flask·fastapi
Betelgeuse762 天前
Django 中间件 4 大钩子 & CBV vs FBV 对比实战
python·中间件·django
北冥有羽Victoria2 天前
Django中间件实战:FBV/CBV日志全兼容
数据库·vscode·后端·python·django·sqlite·开源
源码之家3 天前
计算机毕业设计:Python中药材数据可视化与智能分析平台 Django框架 中药数据分析 医药数据分析数据分析 可视化 爬虫 (建议收藏)✅
python·深度学习·信息可视化·数据分析·django·课程设计
q_35488851533 天前
计算机毕业设计:Python中药材天地网数据挖掘与可视化系统 Django框架 中药数据分析 医药数据分析数据分析 可视化 爬虫 (建议收藏)✅
python·数据挖掘·数据分析·django·flask·课程设计
金玉满堂@bj3 天前
Django \+ MySQL 的标准 Web 项目搭建-初级练习小项目
前端·mysql·django
YJlio3 天前
2023-09-25:ChatGPT 开始支持“看、听、说”,从纯文本正式迈向多模态交互
人工智能·python·科技·chatgpt·django·交互·pygame
YJlio4 天前
7.4.5 Windows 11 企业网络连接与网络重置实战:远程访问、本地策略与故障恢复
前端·chrome·windows·python·edge·机器人·django
知识领航员4 天前
2026年推荐6个AI音乐工具
java·人工智能·python·eclipse·django·php·pygame
Mr数据杨4 天前
【Codex】用知识点配置模块构建考试与教学知识图谱
人工智能·django·知识图谱·codex·项目开发