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.
Tips:
- 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 sdkywg1362@sandbox.com 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.
modular | function |
---|---|
verification | Graphic verification, SMS verification |
user | Registration, login, user center |
Homepage ads | Homepage ads |
commodity | Product list, product search, product details |
Shopping Cart | Shopping cart management, shopping cart consolidation |
order | Confirm order and submit order |
payment | Alipay payment and order commodity evaluation |
MIS system | Data statistics, user management, authority management, commodity management, order management |
2, Project architecture design
1. Project development mode
option | Technology selection |
---|---|
Development mode | Front and rear end separation |
Back end frame | Django2.2.5 |
Front end frame | Vue.js |
2. Key points of knowledge
- Project development mode
- The front and rear ends are separated.
- Django + Vue.js is used to realize the front and rear logic.
- 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
- Prepare profile directory
- Create a new package named settings as the configuration file directory
- Prepare development and production environment profiles
- In configuration package settings, create a new development and production environment configuration file
- Prepare development environment configuration content
- Copy the contents of the default configuration file settings.py to dev.py
2.2 specify the development environment configuration file
- Copy the contents of the default configuration file settings.py to dev.py
4, django project settings
1. TEMPLATES template settings:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
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'@'%'; FLUSH PRIVILEGES; Query OK, 0 rows affected (0.20 sec)
Configure dev.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # database engine 'NAME': 'aerf_mall', # Database name 'USER': 'suifeng', # user name 'PASSWORD': '123456', # password 'HOST': '192.168.42.128', # 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 https://pypi.doubanio.com/simple
3. In dev.py, configure redis cache
# Install Django redis in the virtual machine pip install django-redis
# Configure the cache database used by the current project CACHES = { "default": { # Default storage information: save to library 0 "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://192.168.42.128:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, "session": { # session information: stored in library 1 "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://192.168.42.128:6379/1", "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 SESSION_CACHE_ALIAS = "session"
Document address: https://django-redis-chs.readthedocs.io/zh_CN/latest/
django documentation: https://docs.djangoproject.com/en/2.2/topics/http/sessions/#using-cached-sessions
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 LOGGING = { '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: https://blog.csdn.net/qq_42517220/article/details/105725506
dev.py 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 192.168.235.129 # Enter 192.168.235.129 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 192.168.42.128:8000; # 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 = 'http://192.168.235.129:8000';
//var host = 'http://127.0.0.1:8000';
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 dev.py 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 ../../manage.py startapp users #Note the relative position to manage.py
Download and synchronize, declare in dev.py, create urls.py in users, and register distribution in the main route
from django.contrib import admin from django.urls import path, re_path, include urlpatterns = [ path('admin/', admin.site.urls), # 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 manage.py
/home/pyvip/aerf_mall/aerf_mall/aerf_mall/static/frontend