VSCODE中使用Django处理后端data和data models

4 篇文章 0 订阅
3 篇文章 0 订阅

链接: Python and Django tutorial in Visual Studio Code

链接: https://www.dedao.cn/ebook/reader?id=rEQKv6PKN7rEo2Gxg96ZjApyMvQVlw5q1rwXb14PJzDkYaReqd8n5LOmB8d7egBx

MVC的理解

在实际的程序中采用MVC的方式进行任务拆分。 Model(模型)负责封装应用程序的数据和业务逻辑部分。Model包含数据结构,数据处理逻辑以及相关的操作方法,用于对数据进行增删改查等操作。Model(模型)View (用户界面)和Controller(用户交互逻辑)相分离的方式有下面的好处:

1,相同业务逻辑可以被不同的View(视图)复用。

2,Controller(控制器)通过用户的输入更新模型(Model)的状态,模型(Model)的变化可以自动反应在关联的视图(View)上。

3,业务规则和数据访问(Model部分)独立于具体的展示形式(View)和用户交互流程(controll), 让代码更加可维护,可复用。便于编程的标准化和工程化。

Django的解决方案

在很多实际的程序中,需要使用存储与数据库的数据。Django通过使用Models来简化对数据库中数据的使用。Django中的Model是python的类,来源于“django.db.models.Model”。原则上代表特定的数据库对象(通常为 表单)。类在 app目录下的 models.py文件里进行定义。

Django通过在程序中定义的models来管理数据库。Django通过“migratons”功能来自动完成与数据库的交互。基本过程如下:

  1. 更改models.py文件中的models。
  2. 运行Terminal命令“python manage.py makemigrations”。在migrations文件夹下面创建用于更新数据库状态的脚本。
  3. 运行terminal命令 “python manage.py migrate”,执行脚本更新数据库。

Django可以负责数据库的管理,作为编程人员,我们只需要关注在models.py中定义的models就可以了。

在代码中,我们只需要通过模型类来存储和检索数据即可;Django处理底层细节。例外:我们可以使用Django的admin管理工具loaddata命令将数据写入数据库。该命令通常在迁移命令初始化架构后之后,用于初始化数据集。

使用 db.sqlite3 文件时, 我们可以通过 SQLite browser之类的工具直接修改数据库数据。但是需要尽量避免使用这种方法,这会让数据库和APP中的模型数据不一致。 强烈建议: 修改models,运行 makemigrations, 运行 migrate。

数据库选型

Django默认使用db.sqlite3文件作为数据库,该数据库适用于开发阶段。根据Sqlit.org官网When to use SQLite ,SQLite使用于日访问量在10万以下的应用。另外 SQLite不适用于多服务器场景。

基于以上原因,生产环境建议使用 PostgreSQLMySQL, and SQL Server. Django官方文档 Database setup. 云服务文档 Azure SDK for Python .

定义模型(model)

Django中的Model是python的类,来源于“django.db.models.Model”。相关的类在 app目录下的 models.py文件里进行定义。在数据库中每一个Model自动给予编号(字段名id)。其他的字段作为类的属性存在。属性的类型源自django.db.models的类型包括,CharField  (limited text) ,   TextField  (unlimited text),EmailField, URLField, IntegerField, DecimalField, BooleanField, DateTimeField, ForeignKey, ManyToMany等。(详见Django文档 Model field reference .)

每个字段都有属性定义如max_length.  “blank=True”代表该字段为可选项;“null=True”代表可以没有数据。另外还有“choice”属性,用户可以从列表中选择预先定义的值。

示例

在hello目录下的model.py文件中定义“LogMessage”类。

from django.db import models
from django.utils import timezone

class LogMessage(models.Model):
    message = models.CharField(max_length=300)
    log_date = models.DateTimeField("date logged")

    def __str__(self):
        """Returns a string representation of a message."""
        date = timezone.localtime(self.log_date)
        return f"'{self.message}' logged on {date.strftime('%A, %d %B, %Y at %X')}"

截屏

在模型中可以包含使用数据计算出返回值的方法。 models中通常包括__str__方法,用于描述类和实例。

迁移数据库(创建数据库)

由于新创建了model,需要更新数据库。在启动项目虚拟环境的Terminal中运行下面的命令。

python manage.py makemigrations
python manage.py migrate

 在hello/migrations目录下,创建0001_initial.py文件。db.sqlite3数据库文件还不会检查。

通过model使用数据库

通过model和migrate机制,可以通过models来管理数据。在本节中新建form页面,进行注册。修改home页面,显示上述信息。

建立log message页面,输入数据

1, 在hello 的目录中 (该目录有 views.py文件), 创建 forms.py 内容如下。代码的意义,根据数据模型 LogMessage 创建Django表单,该表单包含数据模型的字段。

2,目录 templates/hello 中, 创建新的模版文件 log_message.html 输入如下内容, 代码目的,创建表单,定义POST方法,创建显示为“Log”的按钮.

{% extends "hello/layout.html" %}
{% block title %}
    Log a message
{% endblock %}
{% block content %}
    <form method="POST" class="log-form">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Log</button>
    </form>
{% endblock %}

注意: Django使用 {% csrf_token %} 标签来阻止CSRF攻击。详情见 Cross Site Request Forgery protection .

3,APP的static/hello/site.css 文件中,增加输入窗口宽度定义

input[name=message] {
    width: 80%;
}

4,APP的 urls.py 文件, 增加新网页的路由

path("log/", views.log_message, name="log"),

5,文件 views.py, 定义名字为log_message (URL.py文件在上一步定义的视图名)的视图。视图处理HTTP GET 和POST的后续操作. GET 情况下 (if判断中的 else: 语句), 显示前面步骤中定义的表单. POST 情况下, 程序从表单输入中取值,到数据对象(message)中,设置时间戳,保存对象(当前情况下就是将相关数据写入数据库) 。

# Add these to existing imports at the top of the file:
from django.shortcuts import redirect
from hello.forms import LogMessageForm
from hello.models import LogMessage

# Add this code elsewhere in the file:
def log_message(request):
    form = LogMessageForm(request.POST or None)

    if request.method == "POST":
        if form.is_valid():
            message = form.save(commit=False)
            message.log_date = datetime.now()
            message.save()
            return redirect("home")
    else:
        return render(request, "hello/log_message.html", {"form": form})

6,检查结果之前需要做! 基础页面文件templates/hello/layout.html中, 在 "navbar" 中增加登录信息页签

One more step before you're ready to try everything out! In templates/hello/layout.html, add a link in the "navbar" div for the message logging page:

<!-- Insert below the link to Home -->
<a href="{% url 'log' %}" class="navbar-item">Log Message</a>

7,运行程序,打开网页查看结果。选择 Log Message 页签,显示登录信息:。

Django tutorial: the message logging page added to the app

8,输入信息, 点击 Log, 网页回到home页面. 现在Home页面还不能显示输入的信息。 可以尝试输入更多的信息。 可以使用SQLite Browser 工具检查输入之后数据库的变化。需要以“只读”方式进入数据库,或者在打开程序时退出数据库浏览,否则会出现数据库锁定无法打开程序的问题。

9,终止程序运行,继续下面操作。

建立数据显示页面

10,下面需要做的是,更改Home页面显示输入的信息。用下面的内容替代APP中 templates/hello/home.html 文件 . 此模版需要一个名为 message_list 的变量。如果变量存在 (通过 {% if message_list %} 标签检查), 程序查询此变量 ( {% for message in message_list %} 标签功能) 展示变量的每一行数据. 如果不存在,显示没有数据注册.   `<thead>` 在 HTML 中用于定义表格的头部部分,其中包含列标题或其他表头信息,为表格提供结构化、易读性强的布局,并方便进行样式控制和功能扩展。 `<thead>` 包含了一行 `<tr>`(表格行),该行内有若干个 `<th>` 元素,分别代表表格各列的标题。`<tbody>` 则包含了表格的实际数据行

{% extends "hello/layout.html" %}
{% block title %}
    Home
{% endblock %}
{% block content %}
    <h2>Logged messages</h2>

    {% if message_list %}
        <table class="message_list">
            <thead>
            <tr>
                <th>Date</th>
                <th>Time</th>
                <th>Message</th>
            </tr>
            </thead>
            <tbody>
            {% for message in message_list %}
                <tr>
                    <td>{{ message.log_date | date:'d M Y' }}</td>
                    <td>{{ message.log_date | time:'H:i:s' }}</td>
                    <td>
                        {{ message.message }}
                    </td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    {% else %}
        <p>No messages have been logged. Use the <a href="{% url 'log' %}">Log Message form</a>.</p>
    {% endif %}
{% endblock %}

11, 在 static/hello/site.css中, 增加表单的格式描述

.message_list th,td {
    text-align: left;
    padding-right: 15px;
}

12,文件 views.py, 导入Django_generic的ListView类 , 我们用这个类来执行Home页面。

from django.views.generic import ListView

13,文件 views.py, 替换 home 函数成名为的 HomeListView类, 从类ListView中继承, HomeListView类与 LogMessage 模型绑定。 类中定义函数 get_context_data 以生成模版中的内容.

# Remove the old home function if you want; it's no longer used

class HomeListView(ListView):
    """Renders the home page, with a list of all messages."""
    model = LogMessage

    def get_context_data(self, **kwargs):
        context = super(HomeListView, self).get_context_data(**kwargs)
        return context

14,在 app的 urls.py, 导入数据模型:

from hello.models import LogMessage

15,同样在 urls.py, 为新视图创建新变量,该变量从LogMessage对象中筛选出最近的五个记录(需要再数据库内查询),数据命名为“message_list”, 标记改变量用于home.html

home_list_view = views.HomeListView.as_view(
    queryset=LogMessage.objects.order_by("-log_date")[:5],  # :5 limits the results to the five most recent
    context_object_name="message_list",
    template_name="hello/home.html",
)

16,同样在urls.py, 更改Home页面的路径,使用home_list_view变量:

    # Replace the existing path for ""
    path("", home_list_view, name="home"),

17, 启动程序检查结果

18, 完成后退出运行的程序。

快速回顾

models.py 中定义LogMessage的数据模型,经过migration同步到数据库中对应的表。

views.py 中定义HomeListView的类,类的model为LogMessage

forms.py  中定义 LogMessageForm的类,类的model属性为 LogMessage

urls.py 中“log” 路径,调用视图中的log_message的定义。 Log_message 使用 Forms中定义的LogMessageForm

urls.py 中定义的默认路径“”, 指向home_list_view变量。该变量在urls.py 中定义:数据从LogMessage中筛选,对应的模版为home.html, 

#Terminal命令。在migrations文件夹下面创建用于更新数据库状态的脚本文件。
python manage.py makemigrations
#terminal命令 “python manage.py migrate”,执行脚本更新数据库。
python manage.py migrate

对网页模版进行调试 debugger

 上面的例子中可以看出网页模版处理处理静态数据({% url %} and {% block %})之外,还有进行编程方面的控制功能(如分支流程{% for message in message_list %} 和循环语句 {% if message_list %} ). 上述功能实现的结果就是在编程过程中可能犯错误,这和所有语言是相同的。

幸运的是, python的VSCode扩展提供了我们使用Django的相关调试功能。 "django": true in the debugging configuration (as you do already). The following steps demonstrate this capability:

  1. templates/hello/home.html, 设置两个断点 {% if message_list %} 和 {% for message in message_list %} 对应的行,如下图的黄箭头:

    Django tutorial: breakpoints set in a Django page template

  2. 运行程序开启调试,在浏览器中打开网页。(如果程序已经打开状态,不需要退出运行状态,直接单击debugg工具栏的刷新按钮,在浏览器中刷新就可以了。)程序停在断点{% if %}并在参数面板显示所有的上下文相关数据状态。

    Django tutorial: debugger stopped at breakpoints in the page template

  3. 单击 Step Over (F10) 执行当前语句. VSCode显示程序停在下一个程序语句上,并更改上下文相关参数。查看提示过程断点的位置和不同语句情况下变量的状态。例如, 进入 {% for message in message_list %} 循环语句,检查message中的每次循环的值, 也可以检查 <td>{{ message.log_date | date:'d M Y' }}</td>的对应数值.

  4. Debug Console 窗口中,还可以进行其他的调试检查,查询等工作。 

  5. 当结束单步挑时候可以选择继续(F5)程序自动执行到下一个断点。结束后退出。

可选操作

下面的内容介绍一些对VSCode中使用python的好的工具.

创建程序运行的requirements.txt

我们在分享程序时,不需要将虚拟环境的所有文件都进行分享。使用程序的人可以自己构建需要的环境。

相应的, 开发人员在进行代码分享时也不需要分享虚拟环境,而是分享程序使用的相关依赖包就可以了。依赖包通过requirements.txt文件来分享。

我们可以手工创建这个文件,但是更好的方式是采用 pip freeze 命令来生成该文件。

  1. With your chosen environment selected using the Python: Select Interpreter command, run the Terminal: Create New Terminal command (Ctrl+Shift+`)) to open a terminal with that environment activated.

  2. In the terminal, run pip freeze > requirements.txt to create the requirements.txt file in your project folder.

Anyone (or any build server) that receives a copy of the project needs only to run the pip install -r requirements.txt command to reinstall the packages on which the app depends within the active environment.

Notepip freeze lists all the Python packages you have installed in the current environment, including packages you aren't currently using. The command also lists packages with exact version numbers, which you might want to convert to ranges for more flexibility in the future. For more information, see Requirements Files in the pip command documentation.

创建超级用户使用admin程序

By default, Django provides an administrative interface for a web app that's protected by authentication. The interface is implemented through the built-in django.contrib.admin app, which is included by default in the project's INSTALLED_APPS list (settings.py), and authentication is handled with the built-in django.contrib.auth app, which is also in INSTALLED_APPS by default.

Perform the following steps to enable the administrative interface:

  1. Create a superuser account in the app by opening a Terminal in VS Code for your virtual environment, then running the command python manage.py createsuperuser --username=<username> --email=<email>, replacing <username> and <email>, of course, with your personal information. When you run the command, Django prompts you to enter and confirm your password.

    Be sure to remember your username and password combination. These are the credentials you use to authenticate with the app.

  2. Add the following URL route in the project-level urls.py (web_project/urls.py in this tutorial) to point to the built-in administrative interface:

    # This path is included by default when creating the app
     path("admin/", admin.site.urls),
    
  3. Run the server, then open a browser to the app's /admin page (such as http://127.0.0.1:8000/admin when using the development server).

  4. A login page appears, courtesy of django.contrib.auth. Enter your superuser credentials.

    Django tutorial: default Django login prompt

  5. Once you're authenticated, you see the default administration page, through which you can manage users and groups:

    Django tutorial: the default Django administrative interface

You can customize the administrative interface as much as you like. For example, you could provide capabilities to edit and remove entries in the database. For more information on making customizations, refer to the Django admin site documentation.

Quick Review

#Terminal命令。在migrations文件夹下面创建用于更新数据库状态的脚本文件。
python manage.py makemigrations
#terminal命令 “python manage.py migrate”,执行脚本更新数据库。
python manage.py migrate
#生成依赖文件
 pip freeze > requirements.txt
#安装依赖文件
pip install -r requirements.txt
#创建超级用户使用admin程序
 python manage.py createsuperuser --username=<username> --email=<email>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值