Django后端开发——Django应用及分布式路由

文章目录


参考资料

B站网课:点击蓝色字体跳转

或者复制链接在浏览器打开:https://www.bilibili.com/video/BV1vK4y1o7jH?p=14\&vd_source=597e21cf34ffcdce468ba00be2177e8a


Django应用

创建

终端:

c 复制代码
cd django
cd day03
cd mysite3
python3 manage.py startapp music(应用名)

注册

在settings.py的INSTALLED_APPS中添加应用名即可

分布式路由

news开头的交由news管理

music开头的交由music管理

配置分布式路由

Step1 - 主路由中调用include函数

语法:include('app名字.url模块名')

作用:用于将当前路由转到各个应用的路由配置文件的urlpatterns进行分布式处理

Step2 - 应用下配置urls.py

应用下手动创建urls.py文件

内容结构同主路由完全一样

配置分布式路由的示例

主路由中调用include函数

http://127.0.0.1:8000/music/index

在urls.py中添加:

c 复制代码
    path('music/',include('music.urls'))

import某个已有的库,可以将鼠标放在红波浪线处 Alt+回车 直接导入

应用下配置urls.py

app-new-pythonfile-urls

#http://127.0.0.1:8000/music/index

应用music的urls.py

c 复制代码
from django.urls import path
from . import views

urlpatterns = [
    path('index',views.index_view)
]

效果

练习

创建应用news和sport

终端:在django/day03/mysite3下

c 复制代码
python3 manage.py startapp news
python3 manage.py startapp sport

在settings.py里进行注册

urls.py

添加内容:

复制代码
	#http://127.0.0.1:8000/news/index
    path('news/',include('news.urls')),
    #http://127.0.0.1:8000/sport/index
    path('sport/',include('sport.urls'))

news下新建urls.py(sport 同理)

复制代码
from django.urls import path
from . import views

urlpatterns = [
    #http://127.0.0.1:8000/news/index
    path('index',views.index_view)
]

news的views.py(sport同理)

c 复制代码
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index_view(request):

    return HttpResponse('这是新闻频道首页')

效果



应用下的模版

应用同名嵌套文件夹------避免找不到应用下的模版

news-右键-new-directory-templates-右键-new-directory-news-右键-new-html-index

c 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新闻频道</title>
</head>
<body>

我是新闻频道首页

</body>
</html>

news的views.py:

c 复制代码
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index_view(request):

    return render(request,'news/index.html')

效果:

小结

为了分而治之,引入了应用、分布式路由和应用下的模版。

相关推荐
MrSYJ3 分钟前
Redis 做分布式 Session
后端·spring cloud·微服务
Cache技术分享4 分钟前
318. Java Stream API - 深入理解 Java Stream 的中间 Collector —— mapping、filtering 和 fla
前端·后端
jianghua0016 分钟前
Python中的简单爬虫
爬虫·python·信息可视化
喵手15 分钟前
Python爬虫实战:针对Python官网,精准提取出每一个历史版本的版本号、发布日期以及对应的文档/详情页链接等信息,并最终清洗为标准化的CSV文件!
爬虫·python·爬虫实战·零基础python爬虫教学·python官方数据采集·采集历史版本版本号等信息·导出csv文件
Elieal22 分钟前
SpringBoot 数据层开发与企业信息管理系统实战
java·spring boot·后端
Coder_Boy_23 分钟前
Java开发者破局指南:跳出内卷,借AI赋能,搭建系统化知识体系
java·开发语言·人工智能·spring boot·后端·spring
独自破碎E28 分钟前
BISHI23 小红书推荐系统
java·后端·struts
databook29 分钟前
像搭积木一样思考:数据科学中的“自下而上”之道
python·数据挖掘·数据分析
luoluoal29 分钟前
基于python的医疗问句中的实体识别算法的研究(源码+文档)
python·mysql·django·毕业设计·源码
gustt33 分钟前
构建全栈AI应用:集成Ollama开源大模型
前端·后端·ollama