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

相关推荐
Database_Cool_9 小时前
RAG 混合检索首选:阿里云 Lindorm 向量+全文一体化检索
数据库·阿里云·django·云计算
ednO8nqdR1 天前
Python小游戏制作:如何实现可配置的跨分辨率界面布局
python·plotly·django·virtualenv·scikit-learn·fastapi·pygame
强健的石头2 天前
django文件对象是什么?
数据库·django·sqlite
ai生成式引擎优化技术3 天前
从知识连接到智能组织:WSaiOS认知网络的理论框架与系统设计摘要
网络·python·plotly·django·pygame
大气的小蜜蜂4 天前
基于Python+Django的健身房管理系统实现:核心亮点全流程解析
开发语言·python·django
ai生成式引擎优化技术4 天前
从参数驱动到认知行为驱动:SAI范式的理论转向与WSaiOS认知内核架构
python·架构·django·virtualenv·pygame
agent8974 天前
Elasticsearch 慢查询排查:从 Mapping、分片、分页到聚合优化
大数据·elasticsearch·django
ycydynq4 天前
Django利用中间间 判断页面是否登录,未登录则返回登录页
数据库·django·sqlite
ai生成式引擎优化技术4 天前
WSaiOS:面向认知资产与工程化认知流程的智能操作系统架构
python·架构·django·virtualenv·pygame
2501_947575805 天前
计算机毕业设计之jsp开山车行二手车交易系统
java·开发语言·hadoop·python·信息可视化·django·课程设计