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}")
相关推荐
Wonderful U8 小时前
Python+Django实战|个人博客内容管理系统:搭建轻量化、高自由度的个人动态博客CMS系统
人工智能·python·django
2601_9611940212 小时前
2026初级会计实务教材电子版|章节讲义+习题PDF
python·考研·django·pdf·virtualenv·pygame
2601_9611940214 小时前
2026初级会计经济法基础知识点汇总
python·django·pdf·virtualenv·代理模式·pygame
Wonderful U14 小时前
Python+Django实战 | 智能图书管理系统:从传统人工到全自动数字化管理
python·信息可视化·django
2601_9611940215 小时前
考研政治历年真题库
python·考研·django·virtualenv·pygame·tornado
Wonderful U2 天前
基于 Django Channels 与 WebSocket 的实时聊天室:群聊、私聊、离线消息与持久化存储全实现
python·websocket·django
Wonderful U2 天前
Python+Django实战|校园二手闲置交易平台:从实名认证到交易闭环的完整校园电商解决方案
开发语言·python·django
Dxy12393102162 天前
Django 数据库 ENGINE 完全指南:选错了,性能差 10 倍
python·django
Wonderful U2 天前
基于Python+Django的在线题库与智能阅卷系统:从痛点分析到完整实现
开发语言·python·django
Wonderful U3 天前
基于Python爬虫+Django的轻量化天气预报系统:从数据抓取到可视化展示的完整实战
爬虫·python·django