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}")
相关推荐
麦麦大数据5 小时前
D027 v2 vue+django+neo4j 基于知识图谱红楼梦问答系统 (新增问关系功能;新增知识节点和关系管理功能,neo4j增删改查功能)
vue.js·django·问答系统·知识图谱·neo4j·图谱管理·neo4j增删改查
不爱搬砖的码农14 小时前
宝塔面板部署Django:使用Unix Socket套接字通信的完整教程(附核心配置与问题排查)
python·django·unix
码界奇点1 天前
Django视图从基础到高级的全面解析
数据库·django·sqlite·web·python3.11
清静诗意1 天前
Django from_queryset 源码深度解析:动态生成 Manager 的奥秘
django·queryset
大邳草民1 天前
Django 的动态特性:从 Python 动态机制到框架设计思想
笔记·python·django
麦麦大数据1 天前
D026 vue3+django 论文知识图谱推荐可视化系统 | vue3+vite前端|neo4j 图数据库
前端·django·vue3·知识图谱·推荐算法·论文文献·科研图谱
Q_Q19632884752 天前
python+uniapp基于微信美食点餐系统小程序
spring boot·python·微信·django·flask·uni-app·node.js
麦麦大数据2 天前
D025 摩托车推荐价格预测可视化系统|推荐算法|机器学习|预测算法|用户画像与数据分析
mysql·算法·机器学习·django·vue·推荐算法·价格预测
workflower2 天前
单元测试-例子
java·开发语言·算法·django·个人开发·结对编程
唐古乌梁海2 天前
【python】在Django中,执行原生SQL查询
python·sql·django