current position:Home>Django (make an epidemic data report)

Django (make an epidemic data report)

2022-01-31 05:17:57 Crossover code

Django yes Python web frame , pronunciation [ˈdʒæŋɡo] , Translated into Chinese, it's called “ Ginger dog ”.

Why learn framework ? In fact, we can use Python Code from 0 To 1 Write a web Website , But then you have to write network services 、 Database reading and writing and other underlying code . The role of the framework is to build these underlying infrastructure , We just write business logic .

for instance , A building is a frame , We don't care about the scaffolding at the bottom 、 How is reinforced concrete built , With such a framework, we can live in , And how to design the room inside 、 Decoration is what we care about .

1. First time to know Django

I use Python The version is 3.8, First execute the following statement to install Django

pip install Django
 Copy code 

After installation , Execute the following statement to create Django project

django-admin startproject duma
 Copy code 

The name of the project can be customized , The name of the project I created is duma.

After the command is executed , In the current directory will generate duma Catalog , This directory contains the following source files .

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

Briefly introduce the functions of these files :

  • manage.py: management Django Command line tools for projects , It's like a toolbox , It is often used later
  • mysite/settings.py:Django The configuration file for the project , Such as : Configure what database the project uses 、 What applications are included
  • mysite/urls.py:Django Project URL Statement
  • mysite/asgi.py: As your project runs in ASGI Compatible Web Entry on the server . Temporarily unavailable
  • mysite/wsgi.py: As your project runs in WSGI Compatible Web Entry on the server . Temporarily unavailable

In the later study , We will use 、 Modify the file above , At that time, I will have a deeper understanding of their role .

Run the following command , start-up web service , verification duma Is the project created successfully .

python manage.py runserver
 Copy code 

Carry out orders , You will see the following information output

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

Access in browser http://127.0.0.1:8000/

img

See the page above , This indicates that the project was created successfully .

image.png

Next, we will duma Create an application in the project (app). There can be multiple applications in a project , For example, e-commerce projects can have mall applications 、 Payment application and membership application, etc .

Execute this command , Create an application

python manage.py startapp ncov
 Copy code 

Here's a creation called ncov Application , Use it to make an epidemic data report . The root directory of the project will find a ncov Catalog , Contains the following documents

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

Let's not introduce their functions , These files are basically used later , I'll give you a detailed introduction .

2. Hello, World

“Hello, World” It is a demonstration program for learning any programming language , Now let's use Django Achieve one “Hello, World” web application .

First , stay “nocv/views.py” Create in file index function

from django.http import HttpResponse


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

then , stay ncov Create... In the directory urls.py file , It is used to define ncov The application contains url. Such as : In the application of E-commerce mall , There will be a mall home page url And product details url.

stay urls.py Add a url, To that of the index The function corresponds to .

from django.urls import path

from . import views

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

The first parameter is url The path of , Here is an empty string representing ncov Root path of application ; The second parameter is the url Corresponding view ; The third parameter is the url The name of , Customizable .

Last , stay “duma/urls.py” Add code , take ncov Applied url Sign up to duma In the 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')),

]
 Copy code 

Access in browser ncov Application root path http://127.0.0.1:8000/ncov/

img

If you see the page shown above, it means success . If the started service is shut down , Need to be in duma Directory execution python manager.py runserver Command restart web service .

img

When accessing ncov When applying the root path , The browser will generate a http request ,duma Project web After the service receives the request , according to urls.py Configuration in , call “ncov/views.py” Of documents index Function to handle the request ,index Function HttpResponse The string “Hello, World” Construct as a http Respond to the result and return it to the browser , After the browser receives the response result , Show... On the page “Hello, World” character string .

Careful words , You'll find that HttpResponse('Hello, World!') Follow print('Hello, World') It's like , The latter is what we learn Python Language is the first demo program . Both of them are output “Hello, World” character string , The former is output on the browser , The latter is output on the console ( Command line ) On .

This is the power of the frame , We only focus on business logic , At the bottom http How to request 、 How to respond and how to return to the browser are all done by the framework .

3. Connect to database

An e-commerce website will show a lot of goods , These commodity information are stored in the database . alike ,ncov The application also needs to store epidemic statistics in the database .

open “duma/settings.py” file , find DATABASES To configure , as follows

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

Here are some default configurations .

“default.ENGINE” The representative database engine is sqlite3, Is a lightweight database . You can also change the database engine to MySQL、MongoDB etc. .

“default.NAME” Is the database name , about sqlite For the database, fill in the path of the database , BASE_DIR Represents the root directory of the project , At this point, look at the project root directory and you can find that there are db.sqlite3 file , It is Django Created , We'll use it to store data later .

I wonder if you have such a question , Good database , How is it a file ? In fact, the bottom layer of the database is the file , It's just a set of engine built on the file, which can display the contents of the file in a table , And provide additional information 、 Delete 、 modify 、 Search function . Just like the essence of programmers is human , He is only engaged in programming, so he is called a programmer .

With the 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 , So you can use Django To operate .

stay “ncov/models.py” Create a... In the file Django Model

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() #  Current diagnosis 
    today_new_confirm = models.IntegerField() #  New diagnosis 
 Copy code 

Defined here CyStat Class is used to represent the daily epidemic statistics of each country . Include 7 Attributes , use models Class object in .

stat_dt and cy_name Defined as models.CharField type , Represents the character type . The date is 2021-11-01 This format , Occupy 10 Characters , therefore max_length=10; For country names, generally no more than 50 Characters , So it's max_length=50.

The other fields are statistics , Just use integer .

Having a data model is just 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 , take ncov App registration to duma In the project , stay “duma/settings.py” Found in file INSTALLED_APPS To configure , And add... To the array ncov application , After adding INSTALLED_APPS The 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 
]
 Copy code 

next , Run the following command

python manage.py makemigrations ncov
 Copy code 

After execution , You can see the following output

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

The order will be in “ncov/migration” Create under directory 0001_initial.py file , If you look at the source code, you may not see its function , We can execute the following statement to turn it into sql It's easy to understand .

python manage.py sqlmigrate ncov 0001
 Copy code 

After execution , Output

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;
 Copy code 

It can be found that it is actually a table creation sql, Table name is a combination of application name and model class name , Connect... With underscores . except id Automatically add external , Other field names and definitions are consistent with model class properties .

Last , Execute the following command to complete the table creation operation

python manage.py migrate
 Copy code 

We can open it db.sqlite3 Database to see if it was successful .Mac The computer comes with sqlite3 The command directly opens ,Windows Computers can be installed SQLite Administrator client .

Execute at project root , Open database file

sqlite3 db.sqlite3
 Copy code 

perform .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
 Copy code 

You can find a ncov_cystat Table of , It just follows CyStat Class . In addition, there are many other tables , They are Django The frame comes with , We can ignore .

So we will model CyStat Class and... In the database ncov_cystat Table corresponding to the , Later, we need to query or modify data directly CyStat Class is OK , Instead of writing sql.

Here we can find the use of Django One advantage of the framework —— Isolate the model class from the database ( The jargon is decoupling ). The benefits are , If we want to put our project online in the future sqlite Change the database to MySQL, All we need to do is settings.py Modification in file DATABASES Database engine and database name , Re execute the create table command . Table definition and table query 、 The update logic doesn't need to be changed at all .

img

4. To write web page

The last section , Let's write web Page presentation data . With the above foundation, we know , belong views.py Search in the file ncov_cystat The data table , Then return the data to the browser .

First of all, we need to talk to ncov_cystat Import some data into the table , Refer to previous articles 《 use Python Mapping global epidemic changes 》 Grab it by yourself .

I also prepared some data for “ncov/sql/ Insert epidemic data .sql” Source package , Copy 1 ~ 60 That's ok sql stay sqlite The client can execute .

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);
...
 Copy code 

Reading data , Back to the browser . modify “ncov/views.py” In the document index function

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)
 Copy code 

CyStat.objects Returns the ncov_cystat All the records in the table ,filter It is used to filter the data in the table by field ,'cn' On behalf of China ,cy_name='cn' It means that we only keep domestic data ,order_by Used to follow a field ( Column ) Sort the returned results , Prefix the field name with ‘-’ In descending order , Here we only take the nearest 7 Days of data .

Now we can't be like “Hello, World” That goes straight back to , Because that method returns a string , There is no style . We should return a HTML file , So you need to call reder function , return “ncov/index.html”.

stay ncov Create in directory “templates/ncov/index.html” file , Write the following code

<h3> Domestic epidemic data </h3>

<table border="1">
    <tr>
        <td> date </td>
        <td> Current 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>
 Copy code 

Tables are used in this file to display data , You will find that this is not a pure HTML file . To be precise index.html yes Django A template language defined , It supports writing according to certain syntax Python Code , For example, inside for loop 、stat Use of objects .

render Function can perform parsing template language , Generate pure HTML file , Back to the browser .

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

img

Although the data can be shown , But it's ugly , Need to optimize the front end style .

img

Just said HTML and Django Template languages are markup languages , The grammar is relatively simple , Friends who haven't studied before can find some tutorials to make up for .

To show more beautiful pictures , It's usually done with the help of js Realization , Yes js Basic friends can write their own front-end pages . If it doesn't work pyecharts , It supports Python Code making charts .

download pyecharts GitHub project (github.com/pyecharts/p… “pyecharts/render/templates” Copy the source files in the directory to “ncov/templates” Directory , give the result as follows

img

Continue to modify index function , Change to use pyecharts API Return to line chart .

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(" Current 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())
 Copy code 

The page effect is as follows

img

This effect is like a little .

img

Learn here , We're already getting started Django 了 , Leave an assignment , See if you can do the following .

img

All the code ( Including homework ) Official account Transcode reply “django introduction ” obtain . Today's introduction is just Django A small part , If your feedback is good, we will continue to update later , You can also ask questions at any time .

copyright notice
author[Crossover code],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201310517556973.html

Random recommended