zgq105 / blog

2 stars 0 forks source link

Python WEB开发Django #80

Open zgq105 opened 4 years ago

zgq105 commented 4 years ago

image

1. django是什么?作用?

django是什么? Django是开源的Python Web框架,用于构建安全的、可靠的、可重复利用的web框架。 作用? 帮助开发中快速的构建web应用,提供了基础的web框架服务,使得开发者只需要关注自身的业务功能开发。

2. django项目构建流程

这里以demo项目mysite的构建为例主要流程如下(在win10环境):

2.1 安装django

在cmd窗口下,使用指令pip install Django安装django,安装完之后,使用指令py -m django --version查看安装情况,执行结果如下: image 说明:如果类似上图输出,说明django框架已经安装成功了。

2.2 创建项目

在Django框架中,项目和应用的构建都是使用命令行构建的;接下来就是创建项目mysite,执行指令如下: django-admin startproject mysite 执行之后就会创建如下的文件目录: image 项目目录结果说明:

接下来,运行指令py manage.py runserver启动项目,如下图所示: image 执行之后如果如上图所示,说明项目创建成功了。

2.3 创建应用程序

一般一个项目会有会有多个应用程序(模块或子系统),接下来看看Django是如何创建应用程序的,执行指令py manage.py startapp polls(执行指令的目录需要和manage.py在同一个目录下),创建结果如下: image 应用程序polls目录结构说明:

2.4 配置数据模型和建库

数据模型是一个业务系统中最关键的一部分,是系统的核心,这里主要有两个数据模型,分别是QuestionChoice。一个Question对应多个Choice,两者是1:m的关系,在polls/models.py中配置如下:

import datetime

from django.db import models

# Create your models here.
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

接下来执行指令 py manage.py migrate 来执行数据库模型的构建,如下图所示: image

说明:其中polls_question和polls_choice是自定义的模型,其他均是Django框架自带的数据模型。

2.5 配置admin模块

  1. 创建超级管理员,执行指令 py manage.py createsuperuser 来创建。创建成功后在 http://localhost:8000/admin/中,便可以登录管理用户等信息

  2. 将自定义的数据模型添加到admin中,在polls/admin.py添加如下代码:

    
    from django.contrib import admin
    from .models import Question, Choice

admin.site.register(Question) admin.site.register(Choice)

3. 执行完以上两步之后,我们登录[admin](http://localhost:8000/admin/)中(账户就是1中创建的超级管理员用户),登录结果如下:
![image](https://user-images.githubusercontent.com/17380142/73843785-4596f900-485a-11ea-8678-562c212bcbb5.png)

## 2.6 配置应用路由Url
1. 在polls/urls中添加如下配置:

from django.urls import path from . import views

app_name = 'polls' # 添加应用命名空间 urlpatterns = [

ex: /polls/

path('', views.IndexView.as_view(), name='index'),
# ex: /polls/5/
path('<int:pk>/', views.QuestionDetailView.as_view(), name='detail'),
# ex: /polls/5/results/
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),

]

2. 将应用URL路由信息配置到项目中,在mysite/urls.py中,配置如下:

from django.contrib import admin from django.urls import path,include

urlpatterns = [ path('admin/', admin.site.urls), path('polls/',include('polls.urls')), #将应用路由信息配置到项目中 ]

**说明:admin/是Django项目自带模块,polls/是自己创建的应用,通过关键字include添加到项目中去。**

## 2.7 配置模板
1. 在polls目录下创建templates目录,然后创建对应的html;目录结构如下:
![image](https://user-images.githubusercontent.com/17380142/73844918-7f68ff00-485c-11ea-8361-2dad288bd415.png)

**index.html**代码如下:

{% load static %}

{% if latest_question_list %}

{% else %}

No polls are available.

{% endif %}

**detail.html**代码如下:

{{ question.question_text }}

{% if error_message %}

{{ error_message }}

{% endif %}

{% csrf_token %} {% for choice in question.choice_set.all %}
{% endfor %}
**results.html**代码如下:

{{ question.question_text }}

Vote again?

## 2.8 配置应用的静态资源
1. 在项目中配置像css文件、js文件、图片等静态资源,在应用程序目录polls下创建**static**文件夹,然后创建相应的文件,目录结构如下图所示。
![image](https://user-images.githubusercontent.com/17380142/73845420-90664000-485d-11ea-8580-88e20e3a3ec0.png)

2.在页面中引用静态资源,通过如下代码(以index.html为例)

{% load static %}

## 2.9 配置views

1.在Django中,views起到接口跳转和页面跳转的逻辑,处理请求的响应。有点类似spring mvc中controller的机制。在polls/views.py中代码如下: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import loader

Create your views here.

from django.urls import reverse from django.utils import timezone from django.views import generic

from polls.models import Question, Choice

def index(request):

mvt

# 查询数据库
latest_question_list = Question.objects.order_by('-pub_date')[:5]
# 处理结果数据
output = ', '.join([q.question_text for q in latest_question_list])
template = loader.get_template('polls/index.html')
context = {
    'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))

return render(request, 'polls/index.html', context)

def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question})

def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question})

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

class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list'

def get_queryset(self):
    """Return the last five published questions."""
    return Question.objects.order_by('-pub_date')[:5]

class QuestionDetailView(generic.DetailView): model = Question template_name = 'polls/detail.html'

class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html'



## 2.10 重启项目
执行指令 `py manage.py runserver `,打开网站 [polls](http://localhost:8000/polls/) ,看到如下图所示:
![image](https://user-images.githubusercontent.com/17380142/73846370-631a9180-485f-11ea-8a39-fae2f502cb9c.png)
![image](https://user-images.githubusercontent.com/17380142/73846395-6dd52680-485f-11ea-8da8-85c646e1d46e.png)
![image](https://user-images.githubusercontent.com/17380142/73846407-73cb0780-485f-11ea-8acc-72b77fe48270.png)

**说明:测试数据可以通过 [admin](http://localhost:8000/admin/) 添加。**

# 3. django包含模块
## 3.1 模型(model )
在Django中,模型model也是ORM的设计思想,主要通过实体和数据库表的映射关系来操作数据库,从而简化sql的编程。[参考链接](https://docs.djangoproject.com/en/3.0/topics/db/models/)
## 3.2 视图(view )
在Django中,视图(view )是起到控制器的作用,在view中定义处理请求的方法。整个流程是先通过 URLconfs的配置,然后在view中匹配到处理方法,然后处理请求并相应客户端。(说明:如果做过java开发的同学应该知道Django中的view和spring MVC中的控制器controller的思想类似)
[具体参考](https://docs.djangoproject.com/en/3.0/topics/http/views/)
## 3.3 模板(template )
在Django中,模板template是一种服务端动态渲染页面的模板引擎。[具体参考](https://docs.djangoproject.com/en/3.0/topics/templates/)
## 3.4 表单(Forms)
在Django中,提供了丰富的API来处理表单的请求和响应。[具体参考](https://docs.djangoproject.com/en/3.0/topics/forms/)
## 3.5 管理员(admin)
在Django中,admin是框架自带的后台管理系统,拥有基本的增删改查和权限控制。[具体参考](https://docs.djangoproject.com/en/3.0/ref/contrib/admin/)
## 3.6 安全(Security)
在Django中,框架提供了XSS、CSRF、SQL注入、SSL 等安全机制。[具体参考](https://docs.djangoproject.com/en/3.0/topics/security/)
## 3.7 其他

# 4.小结
Django是一个安全的、高效的Web开发框架。使用Django框架可以简化开发工作,我们只需要专注我们业务模块的开发。