Django之MTV实战(2)

2020-11-04  本文已影响0人  点滴技术

[toc]

Hello, 各位,我回来了,大家别以为我消失了,我还是在的...

最近忙于家里重要事情,不能定期及时更新,请包含...

忙里挑一,我还是在后台默默的码了几篇文章,前提要保证下质量,才能发出来,哈哈!不然...嘿嘿

大家搬好小板凳了,前方的真的高能,文章篇幅有点多,一步一步来...

跟着我走,简单学起来...

1. 回顾知识

上一篇文章已经教会了大家怎么安装Django和简单的配置,相信大家应该早就学会了,那么我们在回忆一下吧,懂的同学可跳过这章节。

1.1 新增工程

django-admin startproject <自定义工程名称>

(py369) [python@localhost Python]$ django-admin startproject devops 

1.2 创建新的APP

python manage.py startapp <自定义APP名称>

(py369) [python@localhost devops]$ python manage.py startapp hello

1.3 注册APP

devops->settings.y里面t添加:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 第一种方式
    'hello.apps.HelloConfig',
    # 第二种方式,直接写hello也行
    'hello',
]

1.4 编写URL和VIEW

在devops下的主路由urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index.index),
    # 引导到hello下的路由URL(也叫子路由)
    path('hello/', include('hello.urls'))
]

在hello下的子路由urls.py

from django.urls import path
from hello import view

app_name = 'hello'
urlpatterns = [
    # 普通url参数
    path('', view.index, name='index'),

hello下的view.py代码:

from django.http import HttpResponse

def index(request):
    return HttpResponse('hello django')

1.5 验证结果如下:

2. 基本概念

2.1 专业术语

MTV简写:

通俗的一句话:用户发送http请求,匹配url后执行view脚本返回模板template,用户看到了网页的展示效果(渲染)

2.2 MTV之视图

2.2.1 request对象

2.2.2 Respone对象

下面详细介绍下...

2.2.3 GET请求

网页输入如下地址,请求返回的结果如下:

2.2.4 POST请求

在devops/setting.py里把csrf关闭,不然会运行报错:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 默认开启防止中间人CSRF攻击,前期先注释掉
    # 'django.middleware.csrf.CsrfViewMiddleware',  
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

网址匹配到路由hello/urls.py配置规则

from django.urls import path
from hello import view

app_name = 'hello'
urlpatterns = [
    path('', view.index, name='index'),
]

后台视图hello/view.py脚本配置如下:

from django.http import HttpResponse, QueryDict

def index(request):
    if request.method == "POST":
        # POST方法
        print(request.method) 
        # body是字节编码,b'year=2020&month=09&day=13'
        print(request.body)  
        # 转换为字典{'year': '2020', 'month': '09', 'day': '13'}
        print(QueryDict(request.body).dict())
        # <QueryDict: {'year': ['2020'], 'month': ['09'], 'day': ['13']}>
        print(request.POST)  
        data = request.POST
        year = data.get('year', '2030')
        month = data.get('month', '9')
        day = data.get('day', '8')

        return HttpResponse("year is {}, month is {}, day is {}.".format(year, month, day))

模拟触发POST流量:

[root@localhost ~]# curl -X POST http://192.168.8.130:8888/hello/ -d 'year=2020&month=09&day=13'
year is 2030, month is 9, day is 13.

看看我们后台接收哪些信息:

2.2.5 QueryDict介绍

在httprequest对象中,GET和POST属性是django.http.QueryDict的实例,它是一个自定义的类似字典的类,用来处理同一个键带多个值。无论使用GET,POST方式,他们最终都是通过QueryDict方法对传入的参数进行处理。

3. MTV之模板

3.1 模板继承

3.1.1 常规手段

3.1.2 模板继承

4. Template模板过滤器

4.1 Django自带常用过滤器

4.2 自定义模板标签和过滤器

5. 模型Model基础

5.1 模型概念

简单理解:模型对应数据库中的表,模型中的一个类对应数据库一张表;

5.1.1 常用字段类型

5.1.2 常用字段参数

6. 建模及同步

6.1 设计一个简单的模型

hello\models.py

#!/usr/bin/env python3
#-*- coding:UTF-8 -*-

from django.db import models

class Devices(models.Model):
    device_name = models.CharField(max_length=32, help_text='设备名称')
    ip = models.CharField(max_length=15, help_text='管理IP地址')
    vendor = models.CharField(max_length=16, help_text='厂商')
    device_type = models.CharField(max_length=6, help_text='设备类型')
    model = models.CharField(max_length=32, help_text='设备型号')
    sn = models.CharField(max_length=32, help_text='序列号')
    os = models.CharField(max_length=16, help_text='操作系统')
    version = models.CharField(max_length=32, help_text='版本')

    def __str__(self):
        return self.device_name

6.2 将模型同步到数据库

7. ORM实现简单的增删改查

7.1 ORM概念

7.2 增 | 删 | 改 | 查

7.2.1 增加数据

(py369) [root@localhost devops]# python manage.py shell

In [1]: from hello.models import Devices
# 实例化对象    
In [4]: D = Devices.objects.all()
In [5]: D
# 暂时还没有数据,为空    
Out[5]: <QuerySet []>  
In [7]: data = {'device_name':'test-sw-01', 'ip':'192.168.1.1', 'vendor':'cisco','device_type':'switch','model':'c3850','sn':'001','os':'ios','version':'15.0'}
# 第一种创建方式(最常用)
In [8]: D.create(**data)
Out[8]: <Devices: test-sw-01>

# 第二种创建方式(防止重复,速度相对较慢):
# 返回一个元组(对象,True或False)
In [10]: data2 = {'device_name':'test-sw-02', 'ip':'192.168.1.2', 'vendor':'cisco','device_type':'switch','model':'c3850','sn':'001','os':'ios','version':'15.0'}
In [14]: D.get_or_create(**data2)
Out[14]: (<Devices: test-sw-02>, True)
In [16]: D
Out[16]: <QuerySet [<Devices: test-sw-01>, <Devices: test-sw-02>]>

7.2.2 删除删除

数据库表中的数据(偷偷增加了一台设备):

In [1]: from hello.models import Devices
# 删除一条记录
 # 第一种方法:get
In [4]: D = Devices.objects.get(device_name = 'test-sw-02')
In [5]: D.delete()
Out[5]: (1, {'hello.Devices': 1})
 # 第二种方法:filter
In [2]: Devices.objects.filter(device_name='test-sw-03').delete()
Out[2]: (1, {'hello.Devices': 1})

# 先还原数据,再删除所有的记录
In [5]: Devices.objects.all().delete()
Out[5]: (3, {'hello.Devices': 3})

7.2.3 修改数据

# 第一种方法:
In [2]: D = Devices.objects.get(device_name='test-sw-03')
In [3]: D.device_name = 'test-sw-13'
In [4]: D.save()
In [5]: Devices.objects.all()
Out[5]: <QuerySet [<Devices: test-sw-01>, <Devices: test-sw-02>, <Devices: test-sw-13>]>

# 第二种方法:
# 指定字段更新,偷偷去看下后台的ID是多少
In [6]: Devices.objects.filter(id=11)
Out[6]: <QuerySet [<Devices: test-sw-13>]>
In [7]: Devices.objects.filter(id=11).update(device_name='test-sw-03')
Out[7]: 1    
In [8]: Devices.objects.get(device_name='test-sw-03')
Out[8]: <Devices: test-sw-03>
        
# 多个字段更新
In [26]: data = {'vendor':'huawei','device_type':'switch','model':'S9303','sn':'001','os':'VRP'}
In [27]: Devices.objects.filter(id=11).update(**data)
Out[27]: 1

最终效果如下(通过数据库查询):

7.2.4 查看数据

8. 打通MTV

8.1 创建模型

参见以上的hello/models.py的配置。

8.2 创建视图view

from django.shortcuts import render
from hello.models import Devices

def devicelist(request):
    # 对象实例化
    devices = Devices.objects.all()
    # {'devices':devices}表示传参
    return render(request, 'hello/device.html', {'devices':devices})

8.3 创建模板

<!--继承母版-->
{% extends "base.html" %}

<!--重写title的内容-->
{% block title %}设备列表{% endblock %}

<!--重写body的内容-->
{% block body %}
<p style="background-color: #77ee77">设备列表</p>
<!--表格-->
<table border="1">
<!--    表头-->
    <thead style="background-color: #00aced" >
        <tr>
            <td>设备名称</td>
            <td>IP地址</td>
            <td>厂商</td>
            <td>设备类型</td>
            <td>型号</td>
            <td>序列号</td>
            <td>操作系统</td>
            <td>版本号</td>
        </tr>
    </thead>
<!--表的正文-->
    <tbody>
        {% for device in devices %}
        <tr>
            <td> {{ device.device_name }} </td>
            <td> {{ device.ip }} </td>
            <td> {{ device.vendor }} </td>
            <td> {{ device.device_type }} </td>
            <td> {{ device.model }} </td>
            <td> {{ device.sn }} </td>
            <td> {{ device.os }} </td>
            <td> {{ device.version }} </td>
        </tr>
        {% endfor %}
    </tbody>
</table>

{% endblock%}

8.4 创建路由视图URL

from django.urls import path
from hello import view

app_name = 'hello'
urlpatterns = [
    path('devicelist', view.devicelist, name='devicelist'),
]

8.5 效果图如下:

大家先不要在意前端效果,后面的项目,再把UI这块优化好,先到这里了,大家学会了吗?

好不容易码完这篇了,大家点个赞吧!


如果喜欢的我的文章,欢迎关注我的公号:点滴技术,扫码关注,不定期分享

上一篇 下一篇

猜你喜欢

热点阅读