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}")
相关推荐
2601_962283881 天前
Django数据库配置(一)
mysql·postgresql·django·sqlite·数据库配置
qq_22589174663 天前
基于Python+Django的LangGraph智能旅游规划系统
python·django·旅游
小刘在重生~3 天前
Django|Excel 批量上传、Form/ModelForm 文件上传、Media 媒体文件配置
python·django·excel
小刘在重生~3 天前
Django|Ajax 入门、JSON 返回、ECharts 图表、文件上传完整笔记
ajax·django·json
2601_962283883 天前
Python 开发框架:Django、Flask和FastAPI
python·django·flask·fastapi·web开发
小刘在重生~4 天前
Django 全套入门笔记|安装、项目创建、ORM、Form、中间件、登录认证
笔记·中间件·django
大模型丫丫6 天前
工业级 RAG 为什么需要 Elasticsearch?
elasticsearch·django·jenkins
Mr数据杨6 天前
【Codex】接入音频转录服务实现课堂语音结构化处理
django·音视频·codex·项目开发
Mr数据杨8 天前
【Codex】用学生考试初始化模块批量准备考试基础数据
django·codex·项目开发
典典分享指南8 天前
Excel SUMIFS 跨表汇总实战:多表条件求和的完整指南
django·flask·numpy·pyqt·fastapi