django的URL配置

1 django如何处理一个请求

首先Django要使用根URLconf模块,通过setting.py配置文件的ROOT_URLCONF来设置。

加载该模块后并查找变量 urlpatterns。这是一个Python的django.conf.urls.url()实例列表。

Django按顺序运行每个URL模式,并在匹配所请求的URL的第一个URL中停止。如下图所示,如果请求的URL是http://127.0.0.1:8000/login,那么当执行到标记的部分URL时,就会结束URL匹配,并跳转到后续的地方执行代码

如果没有正则表达式匹配,或者在此过程中的任何一点出现异常,Django将调用适当的错误处理视图。

2 配置子URL路由表

在任何时候,您urlpatterns都可以"包含"其他URLconf模块。使用include关键字包含app中的子路由

复制代码
from django.urls import include, path
urlpatterns = [
    # ... snip ...
    path('community/', include('django_website.aggregator.urls')),
    path('contact/', include('django_website.contact.urls')),
    # ... snip ...
]

请注意,此示例中的正则表达式没有$(字符串尾匹配字符),但包含尾部斜线。

复制代码
 path('community/', include('django_website.aggregator.urls')),

如上面的代码所示,当URL是http://127.0.0.1:8000/community/...时,只要是community/...的URL都会去django_website这个app下面的aggregator子app的urls.py中的urlpatterns去匹配路由,django_website.aggregator.urls中的path是去掉之前匹配前缀的。

如请求的URL是http://127.0.0.1:8000/community/test/1,当主URL路由表的内容是 path('community/', include('django_website.aggregator.urls')),时,django_website.aggregator.urls的path内容是 path('test/1', xxxx, name="xxxxx")

相关推荐
DXDZ20223 分钟前
12V大功率ESD产品TVS20H12T5G 5000W 200A VC24V助力快充接口浪涌防护
5g·django·symfony
YJlio3 小时前
Registry Usage (RU) 学习笔记(15.5):注册表内存占用体检与 Hive 体量分析
服务器·windows·笔记·python·学习·tcp/ip·django
Psycho_MrZhang4 小时前
Django/Flask/FastAPI简要对比分析
django·flask·fastapi
xj7573065334 小时前
精通django 第二章 视图和URL
数据库·django·sqlite
YJlio1 天前
RAMMap 学习笔记(15.2):Processes / Priority / Summary——从“谁在用”和“谁更重要”看物理内存
开发语言·笔记·python·学习·django·pdf·硬件架构
xj7573065331 天前
《精通Django》第一章 入门
数据库·django·sqlite
哈里谢顿2 天前
验证 list() 会调用 `__len__` 方法的深度解析
python·django
luoluoal2 天前
基于python的语音和背景音乐分离算法及系统(源码+文档)
python·mysql·django·毕业设计·源码
luoluoal2 天前
基于python的英汉电子词典软件(源码+文档)
python·mysql·django·毕业设计·源码
luoluoal2 天前
基于python的旅游景点方面级别情感分析语料库与模型(源码+文档)
python·mysql·django·毕业设计·源码