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}")
相关推荐
WangYaolove131426 分钟前
基于信息安全领域中语义搜索引擎的设(源码+文档)
python·django·毕业设计·源码·计算机源码
WangYaolove131431 分钟前
基于Python的登录网站验证码的生成与识别系统(源码+文档)
python·mysql·django·毕业设计·源码
Franciz小测测34 分钟前
Django 用 Loguru 完美替换标准 Logging,实现优雅的日志管理方案
django
Python毕设指南18 小时前
基于深度学习的旅游推荐系统
python·深度学习·数据分析·django·毕业设计·课程设计
飞Link1 天前
后端架构选型:Django、Flask 与 Spring Boot 的三剑客之争
spring boot·python·django·flask
【赫兹威客】浩哥1 天前
【赫兹威客】框架模板-后端命令行部署教程
python·django
【赫兹威客】浩哥2 天前
【赫兹威客】框架模板-后端bat脚本部署教程
python·django
2501_944526422 天前
Flutter for OpenHarmony 万能游戏库App实战 - 主题切换实现
android·开发语言·javascript·python·flutter·游戏·django
编程小风筝2 天前
Django REST framework实现安全鉴权机制
数据库·安全·django
幸福清风2 天前
【Python】实战记录:从零搭建 Django + Vue 全栈应用 —— 用户认证篇
vue.js·python·django