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

相关推荐
Q_Q5110082857 小时前
python+uniapp基于微信小程序的心理咨询信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
Q_Q51100828512 小时前
python+uniapp基于微信小程序的学院设备报修系统
spring boot·python·微信小程序·django·flask·uni-app
liweiweili12615 小时前
Django中处理多数据库场景
数据库·python·django
workflower1 天前
Fundamentals of Architectural Styles and patterns
开发语言·算法·django·bug·结对编程
局外人LZ1 天前
django rest framework:从零开始搭建RESTful API
python·django·restful·drf
weixin_421133412 天前
Django 的文档接口
python·django·sqlite
合作小小程序员小小店3 天前
web开发,学院培养计划系统,基于Python,FlaskWeb,Mysql数据库
后端·python·mysql·django·web app
B站_计算机毕业设计之家4 天前
推荐系统实战:python新能源汽车智能推荐(两种协同过滤+Django 全栈项目 源码)计算机专业✅
大数据·python·django·汽车·推荐系统·新能源·新能源汽车
茯苓gao4 天前
Django网站开发记录(一)配置Mniconda,Python虚拟环境,配置Django
后端·python·django
码界筑梦坊4 天前
267-基于Django的携程酒店数据分析推荐系统
python·数据分析·django·毕业设计·echarts