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")

相关推荐
Mr数据杨3 小时前
【Codex】用知识点配置模块构建考试与教学知识图谱
人工智能·django·知识图谱·codex·项目开发
Mr数据杨1 天前
【Codex】用班级设置模块维护教学组织基础数据
django·codex·项目开发
斯班奇的好朋友阿法法1 天前
联调注意事项清单
django
forestqq1 天前
基于openeuler2403sp3的容器,打包django运行环境镜像
后端·python·django
俊昭喜喜里1 天前
Allegro/OrCad转换成立创eda文件
python·django
Mr数据杨1 天前
【Codex】用教材配置模块统一管理课程教材体系
django·codex·项目开发
Mr数据杨1 天前
【Codex】用APP绑定教程模块规范移动端接入指引
java·前端·javascript·django·codex·项目开发
阿豪只会阿巴2 天前
【没事学点啥】TurboBlog轻量级个人博客项目——项目介绍
javascript·python·django·html
Mr数据杨2 天前
【Codex】用PPT文案额外描述优化课件生成细节
java·javascript·django·powerpoint·codex·项目开发
Mr.朱鹏2 天前
5.LangChain零基础速通-LCEL链式调用
python·langchain·django·大模型·llm·virtualenv