Key points of python web framework---detailed explanation of Django process


Preface

Python Web Framework Essentials

1. Web application processing flow

Insert image description here

2. The significance of Web program framework

  • Used to build web applications
  • There is no need to rewrite the same code parts for different web applications, and you only need to worry about the core business logic implementation of the web application.

3. The Nature of Web Applications

  • Receive and parse HTTP requests to obtain specific request information
  • Process this HTTP request, that is, complete the business logic processing of this request.
  • Construct and return the processing result - HTTP response

Django process

focus
Insert image description here

focus

  • MVT process: Master the functions of each module of M, V, and T, and understand the MVT process

  • Create Django projects and applications (command)
    – django-admin startproject name
    – python manager.py startapp name

  • Views and URLs
    – View requests and responses
    – URL matching paths

1. Introduction to Django

Introduction to Django

1.1 Introduction

  • Django, pronounced [`dʒæŋɡəʊ], is an open source web development framework written in Python and follows the MVC design. Lawrence Publishing Group developed this framework in order to develop websites focusing on news content, and it was released under the BSD license in July 2005. The name comes from the Belgian jazz musician Django Reinhardt. He is a gypsy who mainly plays guitar and also plays violin. Due to the rapid development of Django in recent years, its applications have become more and more widespread. It was selected as the 2013 SDTimes 100 by the famous IT development magazine SDTimes, ranking 6th in the "API, Library and Framework" category, and is considered a leader in this field.

  • The main purpose of Django is to develop database-driven websites easily and quickly. It emphasizes code reuse, and multiple components can easily serve the entire framework in the form of "plug-ins". Django has many powerful third-party plug-ins, and you can even easily develop your own toolkit. This makes Django very scalable. It also emphasizes rapid development and DRY (DoNotRepeatYourself) principles.

1.2 Features

(1) Heavyweight framework

  • Compared with the Flask framework, Django natively provides numerous functional components to make development easier and faster.

  • Provides automated scripting tools for project engineering management

  • Database ORM support (Object Relational Mapping, English: Object Relational Mapping)

  • template

  • form

  • Admin management site

  • File management

  • Authentication authority

  • session mechanism

  • cache

(2) MVT mode
There is a programming model called MVC. Its core idea is division of labor and decoupling, so that different code blocks can reduce coupling and enhance code reliability. Scalability and portability, achieving backward compatibility.

MVC, which stands for Model-View-Controller, was first proposed by Trygve Reenskaug in 1978. It is a software design pattern invented by Xerox PARC in the 1980s for the programming language Smalltalk. It is designed to apply traditional input, processing, and output tasks to the graphical user interaction model. With the emergence of standard input and output devices, developers only need to focus on the analysis and implementation of business logic. It was later recommended as a design pattern for the Java EE platform of Oracle's Sun Company, and is welcomed by more and more developers using ColdFusion and PHP. Although the original division of labor is no longer used, the idea of ​​​​this division of labor is still used and is widely used in software engineering. It is a typical and widely used software architecture model. Later, the idea of ​​MVC was applied to Web development and was called the Web MVC framework.

MVC pattern description

Insert image description here

  • M is spelled out as Model, which mainly encapsulates access to the database layer and performs operations on adding, deleting, modifying, and querying data in the database.
  • V is spelled out as View, which is used to encapsulate results and generate html content for page display.
  • C is spelled out as Controller, which is used to receive requests, process business logic, interact with Model and View, and return results.

MVT for Django

Insert image description here

  • M is spelled out as Model, which has the same function as M in MVC. It is responsible for interacting with the database and performing data processing.
  • V is spelled out as View, which has the same function as C in MVC. It receives requests, performs business processing, and returns responses.
  • T is spelled out as Template, which has the same function as V in MVC and is responsible for encapsulating and constructing the HTML to be returned.
    Note: The difference lies in the part marked by the black line and black arrow

2. Virtual environment

2.1 Why build a virtual environment?

  • During the development process, when you need to use certain toolkits/frameworks of python, you need to install them online
    – For example, you need to install version 2.2.5 of the Django framework django online

sudo pip install django==2.2.5

  • Tip: Using the above command, Django will be installed under the path /usr/local/lib/python version number/dist-packages
  • Problem: If you want to develop multiple different projects on one computer, you need to use different versions of the same package. If you use the above command to install or update in the same directory, the new version will overwrite the previous version. Other projects will not be able to run.
  • Solution: Virtual Environment
  • Function: The virtual environment can build an independent python running environment, so that the running environment of a single project does not affect each other.
    All virtual environments are located under /home/ Under hidden directory .virtualenvs

2.2 How to set up a virtual environment?

  • Command to install virtual environment:

sudo pip install virtualenv
sudo pip install virtualenvwrapper

After installing the virtual environment, if you are prompted that the mkvirtualenv command cannot be found, you must configure the environment variables:

1. Create a directory to store the virtual environment mkdir $HOME/.virtualenvs

2. Open the ~/.bashrc file and add the following: export WORKON_HOME=$HOME/.virtualenvs source /usr/local/bin/virtualenvwrapper.sh

3. Run source ~/.bashrc

2.3 How to use virtual environment?

    1. Command to create a virtual environment:
      Tip: If you do not specify the python version, the virtual environment of python2 is installed by default
      In python2, create Virtual environment

mkvirtualenv virtual environment name
Example: mkvirtualenv py_django

In python3, create a virtual environment

mkvirtualenv -p python3 virtual environment name
Example: mkvirtualenv -p python3 py3_django
Insert image description here

  • Tips:
    Creating a virtual environment requires an Internet connection
    After the creation is successful, it will automatically work in this virtual environment
    When working in a virtual environment, "virtual environment name" will appear at the beginning of the prompt

  • 2 View the command of the virtual environment:

workon
Insert image description here

  • Commands to use virtual environment:

workon virtual environment name

Example: Using the virtual environment of py3_django
workon py3_django
Insert image description here

  • 3 Command to exit the virtual environment:

deactivate
Insert image description here

  • 4 Command to delete virtual environment:

rmvirtualenv virtual environment name

Example: Delete the virtual environment py3_django

Exit first: deactivate and then delete: rmvirtualenv py3_django
Insert image description here

2.4. How to install the toolkit in a virtual environment?

  • Install the django-2.2.5 package under the python3 version:

pip install package name

Example: Install the django-2.2.5 package pip install django==2.2.5
Insert image description here

  • View the packages installed in the virtual environment:

pip list
Insert image description here

3. Create a Django project

step

  • 1. Create a Django project
    • django-admin startproject name
  • 2. Create sub-applications
    • python manager.py startup app name

3.1 Create project

  • When using the Flask framework, the organization and creation of the project directory need to be created manually by ourselves.
    In django, the project directory can be created with the help of the commands provided by django.

1. Create
The command to create a project is:

django-admin startproject project name

For example: If you want to create a project named bookmanager in the code directory of the desktop, you can execute the following command:

cd ~/Desktop/Code
django-admin startproject bookmanager

After execution, there will be a new directory named bookmanager, which is the newly created project directory.

2. Project directory description
View the created project directory, the structure is as follows
Insert image description here

  • The directory with the same name as the project, here is bookmanager.
  • settings.py is the overall configuration file of the project.
  • urls.py is the project’s URL configuration file.
  • wsgi.py is the project's WSGI-compatible web server entry.
  • manage.py is the project management file through which projects are managed.

3. Run the development server

  • During the development phase, in order to quickly preview the development results, Django provides a lightweight web server written in pure Python, which is only used during the development phase.

Run the server command as follows:

python manage.py runserver ip:end_gut
or:
python manage.py runserver

Note
You do not need to write the IP and port. The default IP is 127.0.0.1 and the default port is 8000.

The following information will be visible after startup:
Insert image description here
Enter the URL "127.0.0.1:8000" in the browser to see the effect.

Insert image description here

  • Django works in Debug mode by default. If files are added, modified, or deleted, the server will automatically restart.
  • Press ctrl+c to stop the server.

3.2 Create sub-applications

  • In web applications, there are usually some business function modules that can be reused in different projects. Therefore, during development, engineering projects are usually split into different sub-functional modules, and each functional module can remain relatively independent. When a specific functional module is needed in other engineering projects, the entire module code can be copied to achieve reuse.

  • In the Flask framework, there is also a concept similar to sub-functional application modules, namely Blueprint.

  • Django's view writing is placed in sub-applications.

1. Create
In Django, creating a sub-application module directory can still be done through commands, namely:

python manage.py startapp sub-application name

manage.py is the management file automatically generated when creating the project above.

For example, in the bookmanager project you just created, if you want to create a user book sub-application module, you can execute:

cd ~/Desktop/code/book
python manage.py startapp book

After execution, you can see that there is an additional subdirectory named book in the project directory.

2. Sub-application directory description
View the project directory at this time, the structure is as follows:
Insert image description here

  • The admin.py file is related to the backend management site configuration of the website.
  • The apps.py file is used to configure information related to the current sub-application.
  • The migrations directory is used to store database migration history files.
  • The models.py file user saves the database model classes.
  • The tests.py file is used to develop test cases and write unit tests.
  • The views.py file is used to write web application views.

3. Register and install the sub-application
Although the created sub-application directory file is placed in the project directory, the Django project cannot directly use the sub-application immediately and needs to be registered. It can only be used after installation.

In the project configuration file settings.py, the INSTALLED_APPS item saves the sub-applications that have been registered and installed in the project. The INSTALLED_APPS in the initial project is as follows:
Insert image description here
How to register and install a sub-application , that is, add the Config class in the sub-application's configuration information file apps.py to the INSTALLED_APPS list.

For example, to add the newly created book sub-application to the project, add 'book.apps.BookConfig' to the INSTALLED_APPS list.
Insert image description here
4. Set up the PyCharm environment
Problem:
Insert image description here
First find the setting options of pycharm:
Insert image description here
Select virtual environment
Insert image description here
Add local virtual environment
Insert image description here
Click a few times to confirm and the problem will be solved
Insert image description here

4. Model

  • The development of current projects is all data-driven.
  • The following is the data relationship of book information management: books and characters are: one-to-many relationship
    Insert image description here
  • You must first analyze the data needed in the project, and then design the database table.
    Insert image description here

Insert image description here
Tips for database development with Django:

  • Model in the MVT design pattern is specifically responsible for interacting with the database. Correspondence (models.py)
  • Since the ORM framework is embedded in the Model, there is no need to program directly to the database.
  • Instead, define model classes, and complete the addition, deletion, modification and query of database tables through model classes and objects.
  • The ORM framework associates rows of database tables with corresponding objects and converts them into each other, making database operations object-oriented.

Steps to use Django for database development:

  • Define model class
  • Model migration
  • Operation database

1. Define model classes

  • Design the model class based on the book table structure:

    • Model class: BookInfo
    • Book name field: name
    • Design the model class based on the character table structure:
    • Model class: PeopleInfo
  • Person name field: name

    • Character gender field: gender
    • Foreign key constraint: book
    • The foreign key must specify the model class it belongs to book = models.ForeignKey(BookInfo)
  • illustrate :

    • The book-character relationship is one-to-many. There can be multiple heroes in a book.
    • There is no need to define the primary key field, it will be added automatically when the table is generated, and the value will grow automatically.
  • According to the design of database table

  • Define the model class in models.py, inherited from models.Model

from django.db import models

Create your models here.
Prepare the model class BookInfo(models.Model) for book list information:
# Create fields, field types...
name = models.CharField(max_length=10)

Model class class PeopleInfo(models.Model) for preparing character list information:
name = models.CharField(max_length=10)
gender = models.BooleanField()
# Foreign key constraints: which book the character belongs to
book = models.ForeignKey(BookInfo,on_delete=models.CASCADE)

2. Model migration (table creation)

  • Migration is completed in two steps:

    • Generate migration files: generate statements to create tables based on model classes

python manage.py makemigrations

    • Execute migration: Create a table in the database based on the statement generated in the first step

python manage.py migrate

Before migration
Insert image description here
After migration
Insert image description here
Tip: By default, sqlite3 database is used to store data

5. Site Management

  • Site: divided into two parts: content publishing and public access
  • The administrator of the website is responsible for viewing, adding, modifying, and deleting data in the part where the content is published.
  • Django can automatically generate management modules based on defined model classes
  • To use Django’s management module, you need to follow the following steps:
    • 1. Localization of management interface
      2. Create administrator
      3. Register model class
      4. Post content to database

5.1 Management interface localization

  • Localization is the local custom of using the displayed language, time, etc. The localization here is Chineseization.
    Simplified Chinese is used in mainland China, and Asia/Shanghai is used as the time zone Time zone, please note that Beijing time zone is not used here.
  • Before localization

Insert image description here

  • After localization
    Insert image description here

5.2 Create administrator

  • Command to create administrator:

python manage.py createsuperuser

  • Enter your username, email, and password as prompted.
    Insert image description here
  • reset Password

python manager.py changepassword username

  • Login site: http://127.0.0.1:8000/admin
    • The server needs to be started

Insert image description here

  • Login to the site successfully
    • There is no book and character management entry in the site interface because the model class is not registered.
      Insert image description here

5.3 Register model class

  • Register the model class in the application's admin.py file
  • Need to import the model module: from book.models import BookInfo,PeopleInfo
    Insert image description here

5.4 Publish content to the database

  • After publishing the content, optimize the model class display
    Prepare the model class for book list information

class BookInfo(models.Model):
# Create field, field type...
name = models.CharField(max_length=10)

def __str__(self):
    """将模型类以字符串的方式输出"""
    return self.name

Insert image description here

6. Views and URLs

  • The site management page is ready, and the next step is to create a public access page.
  • MVT, the design framework for Django.
    • What the user requests in the URL is the view.
    • The view processes the request after receiving it.
    • And return the processing results to the requester.
  • There are two steps required when using views
    • 1. Define the view
    • 2. Configure URLconf

6.1. Defining views

  • A view is a Python function defined in the application's views.py.

  • The first parameter of the view is an object of type HttpRequest, reqeust, which contains all request information.

  • The view must return an HttpResponse object containing the response information returned to the requester.

  • Need to import HttpResponse module: from django.http import HttpResponse

  • Define view function: response string OK! to the client
    Insert image description here

6.2 Configure URLconf

  • The process of finding a view:
    • 1. The requester enters the URL in the browser address bar and requests the website.
    • 2. The website obtains URL information.
    • 3. Then match the written URLconf one by one.
    • 4. If the match is successful, call the corresponding view.
    • 5. If all URLconfs are not matched successfully, a 404 error will be returned.

Insert image description here

  • URLconf entry
    Insert image description here
  • Two steps are required to complete URLconf configuration
    • 1. Define URLconf in the project
    • 2. Define URLconf in the application
  • Define URLconf in project
    Insert image description here
  • Define URLconf in application
    • Tip: A URLconf includes URL rules and views.
      • URL rules are defined using regular expressions.
      • Views are view functions defined in views.py.

Insert image description here

- url匹配过程

Insert image description here

6.3. Testing: Requesting Access

http://127.0.0.1:8000/index/

6.4 Summary

The view processing process is as follows:
Insert image description here

Two steps are required to use views, in no particular order
Configure URLconf
Define views in application/views.py< /span>

7. Template (understand)

Thinking: How does the website return a beautiful page to the client?

hint :

  • A beautiful page requires html, css, and js.
    You can write all these field strings into the view and use them as parameters of HttpResponse() to respond to the client.< /span>

question :

  • The code in the view part is bloated and highly coupled.
    The string defined in this way will not produce any effects or errors.
    The effects cannot be timely Check. It is not easy to find errors in time.

Assumption:

  • Is there a place where the front-end page can be specifically defined so that the effects can be displayed in time, errors can be discovered in time, and the coupling between modules can be reduced!

Solve the problem :template

  • T,Template in MVT design pattern
    In Django, the front-end content is defined in the template, and then the template is handed over to the view for call, all kinds of beautiful and cool things The effect appears.

Template usage steps

  • 1. Create a template
  • 2. Set template search path
  • 3. The template receives the data passed in by the view
  • 4. Template processing data

7.1 Create a template

  • Create the template folder templates in the same directory as the application. The folder name is written in a fixed way.
  • Under the templates folder, create a folder with the same name as the application. For example, Book
  • Create a web template file in the folder with the same name as the application. Example: index.html
    Insert image description here

7.2 Set template search path

Insert image description here

7.3 The template receives data passed in by the view

  • View template loading
    Insert image description here

7.4 Template processing data

Insert image description here

7.5 View template processing data results

Insert image description here

8. Configuration files and dynamic files

8.1 setting configuration file

  • 1. BASE_DIR

    • BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))
      The root directory of the current project. Django will use this to locate related files in the project. We can also use this parameter to construct the file path.
  • 2. DEBUG

    • Debug mode, the initial value is True after creating the project, that is, it works in debug mode by default.

    • effect:

      • Modify the code file and the program will automatically restart
      • When an exception occurs in the Django program, detailed error tracking information is displayed to the front end, for example
        Insert image description here
      • Instead of debugging mode, only Server Error (500) is returned.

Note: Do not run Django in debug mode when deploying online. Remember to modify DEBUG=False and ALLOW_HOSTS.

  • 3. Local language and time zone

  • Django supports localization processing, that is, the display language and time zone support localization.

  • Localization is the local custom of using the displayed language, time, etc. The localization here is Chineseization. Mainland China uses Simplified Chinese, and the time zone uses Asia/Shanghai time zone. Note that Beijing time zone is not used here.

  • The default language and time zone of the initialized project are English and UTC standard time zone

LANGUAGE_CODE = ‘en-us’ # Language
TIME_ZONE = ‘UTC’ # Time Zone # Time Zone

  • Change the language and time zone to mainland China information

LANGUAGE_CODE = ‘zh-Hans’
TIME_ZONE = ‘Asia/Shanghai’

8.2 Static files

  • The CSS, images, and js in the project are all static files. Generally, static files are placed in a separate directory to facilitate management. When calling in an html page, you also need to specify the path of the static file. Django provides a parsing method to configure the static file path. Static files can be placed in the project root directory or in the application directory. Since some static files are common in projects, it is recommended to place them in the project root directory for easy management.

  • In order to serve static files, two parameters need to be configured:

    • STATICFILES_DIRS stores the directory where static files are searched
    • STATIC_URL URL prefix for accessing static files

Example

  • 1) Create a static directory in the project root directory to save static files.
  • 2) Modify the two parameters of the static file in bookmanager/settings.py as follows:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
  • 3) At this time, any static files added in static can be accessed using the URL /static/path of the file in static.

  • For example, if we add an index.html file to the static directory, it can be accessed in the browser using 127.0.0.1:8000/static/index.html.

  • Or we add a subdirectory and file book/detail.html to the static directory, which can be accessed in the browser using 127.0.0.1:8000/static/book/detail.html.

8.3 App application configuration

  • Each application directory contains the apps.py file to save information related to the application.

  • When creating an application, Django will write a configuration class for the application to the apps.py file, such as

from django.apps import AppConfig

class BookConfig(AppConfig):
    name = 'book'

We add this class to the INSTALLED_APPS list in the project settings.py to indicate the registration and installation of applications with this configuration attribute.

  • The AppConfig.name attribute indicates which application this configuration class is loaded into. Each configuration class must contain this attribute, which is automatically generated by default.
  • The AppConfig.verbose_name attribute is used to set the intuitive and readable name of the application. This name will be displayed in the Admin management site provided by Django, such as
from django.apps import AppConfig

class UsersConfig(AppConfig):
    name = 'book'
    verbose_name = '图书管理'

Guess you like

Origin blog.csdn.net/m0_52336378/article/details/131499582