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}")
相关推荐
SelectDB技术团队1 天前
阶跃星辰 Agent 可观测:Apache Doris / SelectDB 的技术能力与实践
django·apache·知识图谱
2401_868534782 天前
MATLAB:车牌识别
python·django
独码侠2 天前
Dify 知识库索引(中):打开源码,拆穿关于“经济索引”的三个谣言
后端·python·django·embedding·知识库·索引·dify
叫我王富贵i3 天前
0基础学Django
后端·python·django
2401_868534784 天前
综合脚本实战!自动备份、清日志、服务器巡检
python·django
weixin_BYSJ19875 天前
springboot酒店管理系统--附源码27436
java·spring boot·python·随机森林·贪心算法·eclipse·django
vx-程序开发5 天前
django医院预约挂号系统---附源码23353
java·javascript·spring boot·python·eclipse·django·php
weixin_BYSJ19875 天前
springboot医疗信息管理系统---附源码17465
java·javascript·spring boot·python·django·flask·php
vx-程序开发6 天前
springboot农产品运输服务平台---附源码75498
java·javascript·spring boot·python·eclipse·django·php
John jj6 天前
拆解 Telegram 群组频道收录市场:三类方案,一个可运行的评分模型,目前TG中文人工评分加模型评分机制——LetsTG收录“快速”、“无门槛”
大数据·后端·python·深度学习·搜索引擎·django·全文检索