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}")
相关推荐
Q_Q19632884752 小时前
python宠物用品商城系统
开发语言·spring boot·python·django·flask·node.js·php
STONE_KKK5 小时前
Django快速入门篇
数据库·django·sqlite
Coding的叶子7 小时前
React Flow 数据持久化:Django 后端存储与加载的最佳实践(含详细代码解析)
django·数据持久化·工作流·智能体·react flow
blues_C7 小时前
二、【环境搭建篇】:Django 和 Vue3 开发环境准备
后端·python·django·vue3·测试平台
Python智慧行囊8 小时前
深入解析 HTTP 中的 GET 请求与 POST 请求
django
Murphy_lx8 小时前
django回忆录(Python的一些基本概念, pycharm和Anaconda的配置, 以及配合MySQL实现基础功能, 适合初学者了解)
后端·python·pycharm·django
Python智慧行囊1 天前
Python Django 的 ORM 编程思想及使用步骤
数据库·python·django·orm
Q_Q19632884751 天前
python动漫论坛管理系统
开发语言·spring boot·python·django·flask·node.js·php
声声codeGrandMaster2 天前
Django框架的前端部分使用Ajax请求一
前端·后端·python·ajax·django
践行见远2 天前
django之视图
python·django·drf