Django 解析路由参数

编写带url参数的路由,4种类型参数

app1.url.py

复制代码
from django.urls import 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'),
]

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)}")
相关推荐
哈里谢顿2 小时前
django的db性能调优
django
luoluoal5 小时前
基于python的二维码生成算法研究和实现(源码+文档)
python·mysql·django·毕业设计·源码
有梦想的攻城狮7 小时前
Django使用介绍
后端·python·django
xj7573065337 小时前
《精通Django》 第三章 Django模板
数据库·django·sqlite
电商API&Tina18 小时前
京东 API 数据采集接口接入与行业分析
运维·服务器·网络·数据库·django·php
DXDZ20221 天前
12V大功率ESD产品TVS20H12T5G 5000W 200A VC24V助力快充接口浪涌防护
5g·django·symfony
YJlio1 天前
Registry Usage (RU) 学习笔记(15.5):注册表内存占用体检与 Hive 体量分析
服务器·windows·笔记·python·学习·tcp/ip·django
Psycho_MrZhang1 天前
Django/Flask/FastAPI简要对比分析
django·flask·fastapi
xj7573065331 天前
精通django 第二章 视图和URL
数据库·django·sqlite
YJlio2 天前
RAMMap 学习笔记(15.2):Processes / Priority / Summary——从“谁在用”和“谁更重要”看物理内存
开发语言·笔记·python·学习·django·pdf·硬件架构