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.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
0001_initial.py
models.py
static/
polls/
images/
background.gif
style.css
templates/
polls/
detail.html
index.html
results.html
tests.py
urls.py
views.py
templates/
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 = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_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/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_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控制器

架构

django架构简介_html

用户从最右侧开始访问,请求(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 path

from . import views

app_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层函数的映射

django架构简介_python_02

映射到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 += 1
selected_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 models


class 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官方教程