It is everyone's responsibility to protect the epidemic. I made an epidemic data report with Django to see if you are suitable to go out today

Keywords: Python Django Back-end

Django is a Python web framework[ ˈ d ʒ æ ŋɡ o] It is called "Ginger dog" in Chinese.

Why learn framework? In fact, we can write a web site from 0 to 1 in Python code, but in that case, we need to write the underlying code such as network service, database reading and writing. The role of the framework is to build these underlying infrastructure. We can only write business logic.

For example, a building is a frame. We don't care how the scaffolding and reinforced concrete on the ground floor are built. As long as we have such a frame, we can live in it, and what we care about is how to design and decorate the rooms inside.

1. First meet Django

The Python version I use is 3.8. First execute the following statement and install Django

pip install Django

``

After the installation is completed, execute the following statement to create the Django project

django-admin startproject duma

The project name can be customized. The project name I created is duma.

After the command is executed, a duma directory will be generated in the current directory, which contains the following source files.

duma/
    manage.py
    duma/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

Briefly introduce the functions of these files:

  • manage.py: the command-line tool for managing Django project is like a toolbox, which will be often used later

    mysite/settings.py: the configuration file of Django project, such as configuring what databases and applications the project uses

    mysite/urls.py: URL declaration for Django project

    mysite/asgi.py: as the portal for your project running on an ASGI compatible Web server. Not for the time being

    mysite/wsgi.py: serves as the portal for your project running on a WSGI compliant Web server. Not for the time being

In the later study, we will use and modify the above files, and we will have a deeper understanding of their role at that time.

Run the following command to start the web service and verify whether the duma project is created successfully.

python manage.py runserver

When you execute the command, you will see the following information output

Starting development server at http://127.0.0.1:8000/

Access in browser http://127.0.0.1:8000/

See the above page, indicating that the project was created successfully.

Next, we will create an app in the duma project. There can be multiple applications in a project, such as mall applications, payment applications and member applications in e-commerce projects.

Execute this command to create an application

python manage.py startapp ncov

Here, an application named ncov is created to report epidemic data. The project root directory will find an ncov directory containing the following files

ncov/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

I won't introduce their functions first. These files will be used later. They will be introduced in detail at that time.

2 Hello, World

"Hello, World" is a demo program for learning any programming language. Now we use Django to implement a "Hello, World" web application.
First, create the index function in the "nocv/views.py" file

from django.http import HttpResponse


def index(request):
    return HttpResponse('Hello, World!')

Then, create the urls.py file in the ncov directory, which is used to define the url contained in the ncov application. For example, in the application of E-commerce mall, there will be the url of the mall home page and the url of commodity details.
Add a url in the urls.py file to correspond to the index function.

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

The first parameter is the path of the url, where the empty string represents the root path of the ncov application; The second parameter is the view corresponding to the url; The third parameter is the name of the url, which can be customized.
Finally, add code in "duma/urls.py" and register the url of ncov application in duma project. The added code is as follows

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('ncov/', include('ncov.urls')),

]

Accessing the ncov application root path in the browser http://127.0.0.1:8000/ncov/

If you see the page shown above, it means success. If the started service is closed, you need to execute the python manager.py runserver command in the duma directory to restart the web service.

When accessing the ncov application root path, the browser will generate an http request. After receiving the request, the web service of duma project will call the index function of "ncov/views.py" file to process the request according to the configuration in urls.py. In the index function, HttpResponse is used to construct the string "Hello, World" into an http response result and return it to the browser, After receiving the response result, the browser displays the "Hello, World" string on the page.
If you are careful, you will find that HttpResponse('Hello, World! ') is very similar to print('Hello, World'), which is the first demonstration program when we learn Python language. Both of them output "Hello, World" strings, the former on the browser and the latter on the console (command line).
This is the power of the framework. We only focus on the business logic. The framework helps us do a good job in how the underlying http requests, responds and returns to the browser.

3 connect to the database

An e-commerce website will display many goods, and the information of these goods is stored in the database. Similarly, ncov applications also need to store epidemic statistics in the database.
Open the "duma/settings.py" file and find the DATABASES configuration as follows

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

Here are some default configurations.
"default.ENGINE" means that the database engine is sqlite3, which is a lightweight database. You can also change the database engine to MySQL, MongoDB, etc.

"default.NAME" is the database name. For SQLite database, fill in the database path here, BASE_DIR represents the project root directory. At this time, if you look at the project root directory, you can find that there is a db.sqlite3 file created by Django. Later, we will use it to store data.

I don't know if you have such a question. How is a good database a file? In fact, the bottom layer of the database is the file. It just establishes a set of engine on the file, which can display the contents of the file in a table, and provide the functions of adding, deleting, modifying and searching. Just as the essence of a programmer is also a human being, he is only engaged in programming, so he is called a programmer.

With a database, you also need to create tables in the database. Generally speaking, you can use database commands to create tables directly. But because we use a framework, we can use Django to operate.

Create a Django model in the "ncov/models.py" file

from django.db import models


class CyStat(models.Model):
    stat_dt = models.CharField(max_length=10) # date
    cy_name = models.CharField(max_length=50) # Country name
    confirm = models.IntegerField() # Cumulative diagnosis
    dead = models.IntegerField() # Cumulative death
    heal = models.IntegerField() # Cumulative cure
    today_confirm = models.IntegerField() # Existing diagnosis
    today_new_confirm = models.IntegerField() # New diagnosis

The CyStat class is defined here to represent the daily epidemic statistics of each country. It includes 7 properties, which are initialized with the class object in models.

stat_dt and cy_name is defined as the model.charfield type, representing the character type. The date is in the format of 2021-11-01, which takes 10 characters, so max_length=10; Generally speaking, the country name does not exceed 50 characters, so its max_length=50.

The other fields are statistics, which can be integer.

Having a data model is only the first step. How do we get the data? At this time, you need to associate the model with the tables in the database.

First, register the ncov application in the duma project and find installed in the "duma/settings.py" file_ APS configuration, and add ncov application in the array. After adding, it is installed_ The APS array is as follows

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ncov.apps.NcovConfig'  # Register ncov application

Next, run the following command

python manage.py makemigrations ncov

After execution, you can see the output of the following information

Migrations
for 'ncov':
  ncov/migrations/0001_initial.py
    - Create model CyStat

This command creates 0001 in the "ncov/migration" directory_ Initial.py file. If you look at the source code, you may not see its function. We can execute the following statement to convert it into sql, which is easy to understand.

python manage.py sqlmigrate ncov 0001

Output after execution

BEGIN;
--
-- Create model CyStat
--
CREATE TABLE "ncov_cystat" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "stat_dt" varchar(10) NOT NULL, "cy_name" varchar(50) NOT NULL, "confirm" integer NOT NULL, "dead" integer NOT NULL, "heal" integer NOT NULL, "today_confirm" integer NOT NULL, "today_new_confirm" integer NOT NULL);
COMMIT;

It can be found that it is actually a table creation sql. The table name is a combination of application name and model class name, which is connected with an underscore. Except that id is automatically added, other field names and definitions are consistent with model class attributes.

Finally, execute the following command to complete the table creation operation

python manage.py migrate

We can open the db.sqlite3 database to see if it is successful. The SQLite3 command comes with the Mac, and the SQLite Administrator client can be installed on the Windows computer.
Execute in the project root directory and open the database file

sqlite3 db.sqlite3


implement .tables View tables in the database
sqlite> .tables
auth_group django_admin_log
auth_group_permissions django_content_type
auth_permission django_migrations
auth_user django_session
auth_user_groups ncov_cystat
auth_user_user_permissions

You can find a file named ncov_cystat table, which is the table created according to the CyStat class. In addition, there are many other tables, which come with the Django framework, and we can ignore them first.

In this way, we compare the model CyStat class with ncov in the database_ Corresponding to the CyStat table, we need to query or modify the data in the future. We can directly operate the CyStat class without writing sql.

Here we can find another advantage of using the Django framework - isolating model classes from the database (in jargon, decoupling). The benefit is that if we want to change the sqlite database to MySQL after our project goes online in the future, we only need to modify the database engine and database name of DATABASES in the settings.py file and re execute the table creation command. The table definition, query and update logic of the table do not need to be changed at all.

4 writing web pages

In the last section, let's write a web page to show the data. With the above foundation, we know that ncov should be queried in the views.py file_ The data of the cystat table, and then return the data to the browser.

First, we need to report to ncov_ Import some data into the cystat table.

I also prepared some data and put it in the source code package of "ncov/sql / insert epidemic data. sql", copy 1 ~ 60 lines of sql and execute it on the sqlite client.

sqlite> insert into ncov_cystat(stat_dt, cy_name, confirm, dead, heal, today_confirm, today_new_confirm) VALUES ("2021-09-03", "cn", 123169, 5685, 115024, 2460, 33);
sqlite> insert into ncov_cystat(stat_dt, cy_name, confirm, dead, heal, today_confirm, today_new_confirm) VALUES ("2021-09-04", "cn", 123199, 5685, 115105, 2409, 30);

...

Read the data and return it to the browser. Modify the index function in the "ncov/views.py" file

from django.shortcuts import render

from .models import CyStat


def index(request):
    cy_stats = CyStat.objects.filter(cy_name='cn').order_by('-stat_dt')[:7]
    context = {
        'cy_stats': cy_stats
    }

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

CyStat.objects returns ncov_ For all records in the cystat table, the filter is used to filter the data in the table according to the fields, 'cn' represents China and cy_name = 'cn' means that we only keep domestic data, order_by is used to sort the returned results according to a field (column). Adding '-' before the field name represents descending order. Here we only take the data of the last 7 days.

Now we can't return directly like "Hello, World", because it returns a string without any style. We should return an HTML file, so we need to call the reder function to return "ncov/index.html".

Create the "templates/ncov/index.html" file in the ncov directory and write the following code

<h3>Domestic epidemic data</h3>

<table border="1">
    <tr>
        <td>date</td>
        <td>Existing diagnosis</td>
        <td>New diagnosis</td>
    </tr>
    {% for stat in cy_stats %}
    <tr>
        <td> {{ stat.stat_dt }} </td>
        <td> {{ stat.today_confirm }} </td>
        <td> {{ stat.today_new_confirm }} </td>
    </tr>
    {% endfor %}
</table>

The file uses tables to display data, and you will find that this is not a pure HTML file. To be exact, index.html is a template language defined by Django. It supports writing Python code according to certain syntax, such as the use of for loops and stat objects.

The render function can parse the template language, generate pure HTML files, and return them to the browser.

Access in browser http://127.0.0.1:8000/ncov/ , you can see the following page

Although the data can be displayed, it is ugly and needs to optimize the front-end style.

The HTML and Django template languages just mentioned are both markup languages, and the syntax is relatively simple. Friends who haven't learned before can find some tutorials to make up for them.

To display beautiful pictures, it is generally realized with the help of js. Friends with the foundation of js can write their own front-end pages. If you don't have pyecarts, it supports making charts in Python code.

Download the pyecarts GitHub project( https://github.com/pyecharts/pyecharts )Source code, copy the source file in the "pyechards / render / templates" directory to the "ncov/templates" directory, and the results are as follows

Continue to modify the index function and use the pyecharts API to return the line chart instead.

from django.http import HttpResponse
from django.shortcuts import render
from pyecharts.charts import Line, Map
from pyecharts import options as opts

from .models import CyStat


def index(request):
    cy_stat = CyStat.objects.filter(cy_name='cn').order_by('-stat_dt')[:14]

    stat_list = [x.stat_dt for x in cy_stat]
    stat_list.reverse()

    today_confirm_list = [x.today_confirm for x in cy_stat]
    today_confirm_list.reverse()

    today_new_confirm_list = [x.today_new_confirm for x in cy_stat]
    today_new_confirm_list.reverse()

    c = (
        Line()
        .add_xaxis(stat_list)
        .add_yaxis("Existing diagnosis", today_confirm_list)
        .add_yaxis("New diagnosis", today_new_confirm_list)
        .set_global_opts(title_opts=opts.TitleOpts(title="Domestic epidemic data"))
    )
    return HttpResponse(c.render_embed())

The page effect is as follows

The effect is like this.

After learning this, we have started Django. Leave an assignment to see if you can make the following effects.

Reply to "getting started with Django" for all codes (including homework). Today's introduction is only a small part of Django. If you have good feedback, you will continue to update it later. You can ask questions at any time.

Posted by gkwhitworth on Wed, 10 Nov 2021 12:43:13 -0800