Knowledge summary of open source web framework django

Knowledge summary of open source web framework django (7)

1, Project introduction

1. Project demand analysis

Demand analysis reason:

  • Can understand the business process and main business requirements of the project as a whole.
  • In the project, demand driven development. That is, developers need to take requirements as the goal to realize business logic.

Demand analysis method:

  • In the enterprise, the requirements are analyzed with the help of product prototype diagram.
  • After the requirement analysis, the front end develops the front end page according to the product prototype, and the back end develops the corresponding business and response processing.

Requirements analysis content:

  • Page and its business process and business logic.


  • We now use the sample website as a prototype to analyze the requirements.

2. Introduction to main pages of the project

2.1. Home page advertisement

2.2. Registration

2.3. Login

2.4. Personal information

2.5. Receiving address

2.6. My order

2.7. Change password

2.8. Commodity list

2.9. Product search

2.10. Commodity details

2.1. Shopping cart

2.12. Settlement order

2.13. Submit order

2.14. Alipay payment

2.15. Payment result processing

2.16. Evaluation of order goods

Buyer account The sandbox interface needs to be turned off, otherwise it will prompt the phishing website.

3. Summarize the main modules of the project

In order to facilitate project management and multi person collaborative development, we divide the functions into different modules according to the requirements.

In the future, each module will be managed and decoupled according to a sub application in the project.

verificationGraphic verification, SMS verification
userRegistration, login, user center
Homepage ads Homepage ads
commodityProduct list, product search, product details
Shopping CartShopping cart management, shopping cart consolidation
orderConfirm order and submit order
paymentAlipay payment and order commodity evaluation
MIS systemData statistics, user management, authority management, commodity management, order management

2, Project architecture design

1. Project development mode

optionTechnology selection
Development modeFront and rear end separation
Back end frameDjango2.2.5
Front end frameVue.js

2. Key points of knowledge

  1. Project development mode
    • The front and rear ends are separated.
    • Django + Vue.js is used to realize the front and rear logic.
  2. Project operation mechanism
    • Proxy service: Nginx server (reverse proxy)
    • Static service: Nginx server (static homepage, product details page,...)
    • Dynamic service: uwsgi server (alpha mall business scenario)
    • Back end services: MySQL, Redis, Celery, Docker, FastDFS, Elasticsearch
    • External interface: Rong Yun, Alipay

3, Project creation and configuration

1. Create project

1.1 enter the local project directory

mkdir df17
cd df17
mkdir aerf_mall
cd aerf_mall

1.2 create alpha mall virtual environment and install Django framework

mkvirtualenv -p python3 aerf_mall
pip install django==2.2.5

1.3 create Django project of alpha mall

django-admin startproject aerf_mall

1.4 configuring pycharm items

Note: when the virtual machine has multiple image files, if the same virtual environment name exists in different images, the project may not be executed.

Solution: delete all interpreters in pycharm and re create

2. Configure development environment

2.1 create a new configuration file
  1. Prepare profile directory
    • Create a new package named settings as the configuration file directory
  2. Prepare development and production environment profiles
    • In configuration package settings, create a new development and production environment configuration file
  3. Prepare development environment configuration content
    • Copy the contents of the default configuration file to

      2.2 specify the development environment configuration file

4, django project settings

1. TEMPLATES template settings:
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
2. Configure mysql database

Login to mysql

mysql -uroot -pqwe123

View existing databases and existing user names

SELECT DISTINCT CONCAT('User: ''',user,'''@''',host,''';') AS query FROM mysql.user;

show databases;

Delete user: drop user 'suifeng10' @ '%';

Delete database: drop database < database name >;

Create a new database

create database aerf_mall charset=utf8;
Query OK, 1 row affected (0.00 sec)

Create user

# New user password 
create user suifeng identified by '123456';
Query OK, 0 rows affected (0.00 sec)

to grant authorization

# Give ownership and limit the stock, followed by the account number
grant all on aerf_mall.* to 'suifeng'@'%'; 
Query OK, 0 rows affected (0.20 sec)


    'default': {
        'ENGINE': 'django.db.backends.mysql',             # database engine
        'NAME': 'aerf_mall',                              # Database name
        'USER': 'suifeng',                                  # user name
        'PASSWORD': '123456',                            # password
        'HOST': '',                                # Host IP
        'PORT': 3306                                        # port

Install the python driver of mysql database and install mysqlclient (for Django2.2 or above, just install mysqlclient)

# Update ubuntu first
sudo apt-get update 
# Then according to the dependent Library
sudo apt-get install default-libmysqlclient-dev
# Then switch to the virtual environment
workon dfaerf
# Install mysqlclient
pip install mysqlclient -i

3. In, configure redis cache

# Install Django redis in the virtual machine
pip install django-redis
# Configure the cache database used by the current project
    "default": { # Default storage information: save to library 0
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
    "session": { # session information: stored in library 1
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",

# Specifies that the session uses cache storage
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# Specifies the cache using the sessoin configuration item

Document address:

django documentation:

4. Configure logger

It is used to record various log information during system operation.

Create a logs folder logs / AERF in the project root directory_ Mall.log, used to store log files

# django's log configuration template
    'version': 1,
    'disable_existing_loggers': False,  # Disable existing loggers
    'formatters': {  # Format of log information display
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
    'filters': {  # Filter logs
        'require_debug_true': {  # django only outputs logs in debug mode
            '()': 'django.utils.log.RequireDebugTrue',
    'handlers': {  # Log processing method
        'console': {  # Output log to terminal
            'level': 'INFO',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        'file': {  # Output log to file
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs/aerf_mall.log/'),  # The location of the log file needs to be created manually
            'maxBytes': 300 * 1024 * 1024,
            'backupCount': 10,
            'formatter': 'verbose'
    'loggers': {  # Logger
        'django': {  # A logger named django is defined
            'handlers': ['console', 'file'],  # The log can be output to the terminal and file at the same time
            'propagate': True,  # Continue delivering log information
            'level': 'INFO',  # The minimum log level received by the logger

5. Time zone configuration

# update language
LANGUAGE_CODE = 'zh-hans'
# Modify time zone
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True
# Use time zone
USE_TZ = True

6. Static file configuration (focus of this lesson)

Learning reference: file configuration, import static folder

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static') #Static files for web sites
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/frontend'),]

Installing nginx

# Installing nginx
sudo apt update -y
sudo apt install nginx -y
# Start nginx and check the startup status. If it is active(running), it means the startup is successful
ps -ef | grep nginx
# Port 80 is enabled by default. You can check whether web services are provided
curl -I

# Enter in the browser to check whether the startup is successful

Modify the configuration file default of nginx; Sudo VIM this file

#Add a new location item under the server node, pointing to the ip and port of uwsgi
server {
	# Static file
    location /static {
        alias /home/pyvip/projects/aerf_mall/aerf/aerf/static/frontend/;#Pay attention to modifying the path
	location /{
		#uwsgi_pass; # To annotate this line
		#include /etc/nginx/uwsgi_params;  # To annotate this line

Press "Esc", ":", "wq" to save and exit editing.

After vim modification, you can use the command: sudo nginx -t to test whether there is a problem with the modified nginx

Restart nginx

sudo systemctl restart nginx

Modify the host.js file
//Save backend API server address
var host = '';
//var host = '';

nginx management command:

Stop nginx, start nginx, restart nginx, reload configuration file, start nginx automatically, do not start nginx automatically

sudo systemctl stop nginx
sudo systemctl start nginx
sudo systemctl restart nginx
sudo systemctl reload nginx
sudo systemctl disable nginx
sudo systemctl enable nginx

7. Create an application. Create an apps directory under the project root directory to store all sub applications.

Then go to the file and add the following settings

import os, sys

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))  #Defines the priority of the search path. The sequence number starts from 0, indicating the maximum priority

Then right-click the apps folder and the project root folder respectively, add them to the Source Root, and optimize the import path (pychart prompt).

In the virtual machine, cd apps, use the command to create an application

python ../../ startapp users  #Note the relative position to

Download and synchronize, declare in, create in users, and register distribution in the main route

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

urlpatterns = [
    # The regular value of the total route is empty, which means that the total route will not match any path prefix, and the complete path will be handed over to the sub route for matching
    re_path(r'', include('users.urls')),

Document Authorization:

chmod u=rwx,g=rwx,o=r,+x


I wish you all success in learning python!

Tags: Python Front-end Django Ubuntu

Posted on Tue, 09 Nov 2021 21:45:16 -0500 by ps2gamer