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

相关推荐
U盘失踪了1 天前
Django Bootstrap 下载到本地使用,避免 CDN 超时
python·django·bootstrap
U盘失踪了1 天前
Django 登录注册功能实现
后端·python·django
U盘失踪了1 天前
Django 登录注册功能实现-样式优化
后端·python·django
B站计算机毕业设计之家1 天前
大数据项目:基于python电商平台用户行为数据分析可视化系统 电商订单数据分析 Django框架 Echarts可视化 大数据技术(建议收藏)
大数据·python·机器学习·数据分析·django·电商·用户分析
凡梦千华2 天前
django迁移表结构和数据
数据库·django
猎人everest2 天前
Django Rest Framework (DRF) 核心知识体系梳理与深度讲解
后端·python·django
码界奇点2 天前
基于Django与Ansible的智能运维管理系统设计与实现
运维·python·django·毕业设计·ansible·源代码管理
Q_Q5110082853 天前
python+django/flask+vue的大健康养老公寓管理系统
spring boot·python·django·flask·node.js
非鱼feiyu3 天前
自关联数据表查询优化实践:以 Django + 递归 CTE 构建树结构为例
数据库·后端·django
Q_Q19632884753 天前
python+django/flask+vue的多媒体素材管理系统
spring boot·python·django·flask·node.js·php