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}")
相关推荐
IT策士1 小时前
Django 从 0 到 1 打造完整电商平台:系列总结 + 项目演示与后续扩展
后端·python·django
俊哥工具4 小时前
无广告免费壁纸工具,手机电脑壁纸随心更换
python·智能手机·django·计算机外设·virtualenv·pygame
小熊Coding9 小时前
Python二手图书市场行为分析系统
开发语言·爬虫·python·django·计算机毕业设计·数据可视化分析·二手图书分析系统
码界筑梦坊11 小时前
150-基于Python的中国海洋水质数据可视化分析系统
开发语言·python·信息可视化·django·毕业设计
JavaWeb学起来1 天前
Django学习教程(一)Django介绍和环境准备
django·python web·web框架·django教程
IT策士1 天前
Django 从 0 到 1 打造完整电商平台:使用 Celery 异步发送邮件/短信
后端·python·django
IT策士1 天前
Django 从 0 到 1 打造完整电商平台:商品缓存优化(Redis)
redis·缓存·django
IT策士1 天前
Django 从 0 到 1 打造完整电商平台:Nginx + uWSGI 部署 Django 项目
nginx·django·sqlite
Dxy12393102161 天前
Django如何获取请求IP?从踩坑到最佳实践
tcp/ip·django·sqlite
IT策士2 天前
Django 从 0 到 1 打造完整电商平台:我的订单列表与订单详情
后端·python·django