django架构简介
Django特性
ORM。models层建立数据类与数据库中数据形成ORM映射关系
MTV架构。与MVC架构有
小小
的区别,controller
的功能被分化在了url dispatcher
(urls.py文件)与views
两个模块中
目录结构
Django把一个网站所有内容称作一个project
,每个模块称作app
例如如下目录结构中,项目名称mysite为一个project, 文件夹mysite/mysite
称为项目的根配置文件
,其中的文件mysite/mysite/urls.py
提供了url的一级路由,路由到各个app
中,例如polls
这个app
mysite/manage.pymysite/__init__.pysettings.pyurls.pyasgi.pywsgi.pypolls/__init__.pyadmin.pyapps.pymigrations/__init__.py0001_initial.pymodels.pystatic/polls/images/background.gifstyle.csstemplates/polls/detail.htmlindex.htmlresults.htmltests.pyurls.pyviews.pytemplates/admin/base_site.html
部分模块功能解释如下
mysite\mysite\settings.py
: 项目的配置项,类似于maven,有着如下形式的内容
from pathlib import Path# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-#3+p28vqi&m@pj(ito4frk2%57ic^27cn@ip-i4vu(4)z6ow43'# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = ['polls.apps.PollsConfig','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',
]MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',
]ROOT_URLCONF = 'mysite.urls'TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [],'APP_DIRS': True,'OPTIONS': {'context_processors': ['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},},
]WSGI_APPLICATION = 'mysite.wsgi.application'# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databasesDATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3','NAME': BASE_DIR / 'db.sqlite3',}
}# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validatorsAUTH_PASSWORD_VALIDATORS = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',},{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',},{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',},{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',},
]
mysite\mysite\urls.py
我把它称作根路由或一级路由。之所以这么取名,因为在每个所谓app
中,还有第二级url控制器
架构
用户从最右侧开始访问,请求(url)首先进入根目录下的url控制器(或称url dispatcher
)中。url dispatcher
中有着如下形式的函数
urlpatterns = [path('polls/', include('polls.urls', namespace="polls")),path('admin/', admin.site.urls), # django提供的管理工具
]
这个url控制器可以称为一级路由
。提供了project到app的映射
进入某个app
后,还有二级路由,有着如下形式
from django.urls import pathfrom . import viewsapp_name = 'polls'
urlpatterns = [path('', views.IndexView.as_view(), name='index'),path('<int:pk>/', views.DetailView.as_view(), name='detail'),path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),path('<int:question_id>/vote/', views.vote, name='vote'),
]
可见,它提供了app到view层函数的映射
映射到view层某个函数(例如下面的"vote函数"),view会调用models层的数据与templates层的模板,render一个完整的页面返回给用户,有着如下的形式
def vote(request, question_id):question = get_object_or_404(Question, pk=question_id)try:selected_choice = question.choice_set.get(pk=request.POST['choice'])except (KeyError, Choice.DoesNotExist):# Redisplay the question voting form.return render(request, 'polls/detail.html', {'question': question,'error_message': "You didn't select a choice.",})else:selected_choice.votes += 1selected_choice.save()# Always return an HttpResponseRedirect after successfully dealing# with POST data. This prevents data from being posted twice if a# user hits the Back button.return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
可以看出,views层与url dispatcher共同承担了controller层的作用。在架构图中也可以看出,views层可以叫做django数据处理的中心模块也不为过
Models层中建立了一些POCO类,这些POCO类与数据库中的数据形成ORM映射,从而进行各种操作,示例代码如下
# Create your models here.
from django.db import modelsclass Question(models.Model):question_text = models.CharField(max_length=200)pub_date = models.DateTimeField('date published')class Choice(models.Model):question = models.ForeignKey(Question, on_delete=models.CASCADE)choice_text = models.CharField(max_length=200)votes = models.IntegerField(default=0)
templates层也就是一些html文件,形式类似于jsp
,例如下面这段代码
注意{% code %}中写逻辑代码,{{}}中写变量代码
<h1>{{ question.question_text }}</h1><ul>
{% for choice in question.choice_set.all %}<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul><a href="{% url 'polls:detail' question.id %}">Vote again?</a>{% endfor %}
</ul><a href="{% url 'polls:detail' question.id %}">Vote again?</a>
参考
- django架构
- django官方教程
django架构简介相关推荐
- LoadRunner系统架构简介与运行原理
1.LoadRunner系统架构简介 LoadRunner是通过创建虚拟用户来代替真实实际用户来操作客户端软件比如Internet Explorer,来向IIS.Apache等Web服务器发送HTTP ...
- 单线程与多线程网络程序架构简介
文章目录 1 单线程与多线程网络程序架构简介 1.1 服务端单线程处理多客户端 1.2 服务端多进程多端口处理多客户端 1.3 服务端多线程单端口分组处理多客户端 1.4 服务端多线程多端口分组处理多 ...
- Django框架简介
Django框架简介 MVC框架和MTV框架 MVC,全名是Model View Controller,是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model).视图(View) ...
- MVC架构简介及其测试策略
MVC架构简介及其测试策略 https://www.cnblogs.com/rd-ddddd/p/6959232.html 转载于:https://www.cnblogs.com/highpoint ...
- Mysql逻辑架构简介
Mysql逻辑架构简介 整体架构图 和其它数据库相比,MySQL有点与众不同,它的架构可以在多种不同场景中应用并发挥良好作用.主要体现在存储引擎的架构上,插件式的存储引擎架构将查询处理和其它的系统任务 ...
- mme 服务器位置,NB-IOT的网络架构简介
原标题:NB-IOT的网络架构简介 一.NB-iot网络架构 整个NB-IoT网络架构分为五个部分:终端,无线网络,核心网络(EPC),IoT支持平台和应用服务器. 二.NB-iot网络架构简介 1. ...
- Xtensa处理器架构基础-架构简介与常见寄存器
1.架构简介 应用的发展对处理器的需求越来越多样化.与通用处理器架构相比,Xtensa架构的特色在于它是可配置可扩展的微处理器架构.通俗地讲,将其与常见的ARM架构相比,Xtensa架构的特色在于可以 ...
- ARMv8-a架构简介
1. 前言 ARMv8(当前只有A系列,即ARMv8-A)架构,是ARM公司为满足新需求而重新设计的一个架构,是近20年来,ARM架构变动最大的一次.它引入的Execution State.Excep ...
- a55计算机主板,A55架构简介与A55主板赏析
A55架构简介与主板赏析: A55 FCH芯片架构 FCH芯片的角色大概相当于以往的南桥芯片,自身并没有整合显示核心,而是通过UMI接口(而不是HT总线)连接APU整合的显示核心进行输出.A55 FC ...
最新文章
- 企业一般会用哪些软件来提高员工的工作效率?
- Memcache的部署和使用
- TwinVQ解码框图
- 2013-5-17杂乱草稿纸
- Steeltoe 2.4新增代码生成工具、全新入门指南等,助力.NET微服务开发
- ls命令查看文件和目录列表
- asa清空配置_Cisco ASA 管理配置文件
- web项目怎么打包上线_如何打包发布Web Application应用程序
- 转:.Net 中AxShockwaveFlash的解析
- linux系统原理论文3000字,linux操作系统(论文).doc
- Android开发你不知道的TIPS
- 计算机播放音乐无声音,电脑放歌就突然没声音该怎么办
- python半圆_如何在Python中使用Zelle图形制作半圆?
- 非线性方程(组):高维方程解法
- iOS 的UIView 的hitTest的分析
- matlab积分泛函,泛函积分的数学方法概观.pdf
- 计算机照片误删除还能恢复,删除的相片可以恢复吗_电脑误删的照片怎么恢复...
- 基于svg绘制北京地铁图(官网数据来源)
- 微信小程序宠物商城项目源码来了~
- 好利吧:淘宝返利的钱从哪里来的?是我多付了钱吗?