The Python project (Django framework) is built and run on CentOS7.9

Project address: fresh-everyday

Install python3 on CentOS

For the convenience of management, create a folder on the CentOS desktop, download the software package here, right click - open in the terminal

Install python3.9.7:

 wget https://www.python.org/ftp/python/3.9.7/Python-3.9.7.tgz

(The sudo before the command can be removed if you are the root user )

Unzip: 

 tar -zxvf Python-3.9.7.tgz

Enter the decompressed directory:

cd Python-3.9.7

compile

./configure --prefix=/usr/local/python39

  Among them --prefix is ​​the installation directory of Python, where python is specified to be installed, and setuptools and pip tools are also installed

 

 

Install 

make && make install

 If you are prompted that the permissions are not enough, switch to the root user, but keep the current user working directory, and execute the command again

 If the compilation and installation fail: Generally, it is due to the lack of a compilation environment. Usually, the python compilation environment requires zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make. Execute the following command to install again

yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make

installation failed 

Successful installation

 Enter the installation directory

 cd /usr/local/python39

Create a soft link

ln -s /usr/local/python39/bin/python3.9 /usr/bin/python3
ln -s /usr/local/python39/bin/pip3 /usr/bin/pip3

Verify that the configuration is successful:

python3 --version

 The version number appears to be successful

Create a virtual environment using Python

Install the virtual environment

pip3 install virtualenv

If the above information appears, it means that OpenSSL needs to be installed

yum install -y openssl openssl-devel
yum clean all

Execute the command pip3 install virtualenv again and find the same problem.

According to the information, if the --with-ssl parameter is not added during the process of ./configure , the function related to ssl in the default installed software is not available. It just so happens that the pip3 process requires the ssl module, and because it is not specified, this function is not available use.

The solution is to re- enter the python3.9 directory to compile and install, and then execute the command pip3 install virtualenv , and use the following process to compile and install:

cd Python-3.9.7
./configure --with-ssl --prefix=/usr/local/python39

make && make install

Successful installation

Install the virtual environment extension pack

pip3 install virtualenvwrapper

Create a folder to store all virtual environments (here stored in /home/Ruyanjun/desktop/dailyfresh/virtualenvs)

mkdir -p virtualenvs

 edit file~/.bashrc

vim ~/.bashrc

Add the following two lines

export WORKON_HOME=/home/python/virtualenvs
source /usr/local/python39/bin/virtualenvwrapper.sh

 use

source ~/.bashrc

command to take effect

Prompt /usr/bin/python: No module named virtualenvwrapper, because two versions of python 2.x and 3.x are installed, and sudo pip3 install virtualenvwrapper is used by default when I run it.
python2 .x, but there is no corresponding module in python2.x, just add the following command in the bashrc file , and execute the above command again
 

VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3

If the following appears, the execution is successful

 

 Create a virtual environment

mkvirtualenv -p python3 fresh_everyday

fresh_everyday: virtual environment name -p: specify python version

Error:

Cause Analysis: virtualenvThe dependency package is installed in the default Python directory
Solution: Make a soft link

ln -s /usr/local/python39/bin/virtualenv /usr/bin/virtualenv

just recreate 

 Work in a virtual environment

workon fresh_everyday

Exit the virtual environment (do not exit first, the next operations are all performed in the virtual environment ) 

deactivate

Install dependencies required by the project

Install Django 

pip install django

Install pymysql

pip install pymysql

Install the django-tinymce rich text editor

pip install django-tinymce

Install itsdangerous encryption module

pip install itsdangerous

Install celery asynchronous tasks

pip install -U Celery

install redis

pip install redis

Install django-redis

pip install django-redis

Install alipay-sdk-python

pip install alipay-sdk-python

Install django-haystack and whoosh full-text search

pip install django-haystack
pip install whoosh

Installing django-haystack failed, prompting ModuleNotFoundError: No module named '_ctypes',

Solution:

1 Exit the virtual environment and install the external function library (libffi)

yum install libffi-devel -y

Then go back to the python installation process and reinstall python

My steps:

cd ..
yum install libffi-devel -y
cd Python-3.9.7
make && make install
workon fresh_everyday
pip install django-haystack

 Successfully is success

Install the py3Fdfs distributed file system

pip install py3Fdfs==2.1.0

 Install jieba stuttering participle

pip install jieba

Install Pillow ImageField dependencies

python -m pip install Pillow

(The installation may time out, try a few more times or change the source)

mysql installation

install mysql 5.7

The wget command needs to be installed first

wget https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm

Install the MySQL source

yum -y localinstall mysql57-community-release-el7-11.noarch.rpm

install mysql

yum -y install mysql-community-server

There may be problems with the installation process:

 

method:

rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022

 Then execute the installation command

Start the mysql service

systemctl start mysqld

Log in to mysql and change the password

At this time, MySQL has started to run normally, but if you want to enter MySQL, you must first find out the password of the root user at this time. You can find the password in the log file through the following command:

grep "password" /var/log/mysqld.log

Find the password behind root@localhost: and copy it down

log in to mysql

mysql -u root -p

paste copied password

Set password policy

SET GLOBAL validate_password_policy=LOW;

change Password

ALTER USER 'root'@'localhost' IDENTIFIED BY '这里输入你的密码';

Set up remote access

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '输入你的密码' WITH GRANT OPTION;

Refresh permissions 

FLUSH PRIVILEGES; 

project deployment

Create a folder fresh-everyday in the /root directory, and put all the files in https://github.com/Ruyanjun/fresh-everyday/tree/main/app into the fresh-everyday file

You can now clone the project locally, and then use Xftp software to transfer these files to CentOS

Find the haystack directory under the installation directory

pip show django-haystack

 Enter /home/python/virtualenvs/fresh_everyday/lib/python3.9/site-packages/haystack/backends

 Create a ChineseAnalyzer.py file in this directory

touch ChineseAnalyzer.py

 Then vi editor, wq after completion ! save

The content of the file is as follows:

import jieba 
from whoosh.analysis import Tokenizer, Token

class ChineseTokenizer(Tokenizer):
    def __call__(self, value, positions=False, chars=False,
                keeporiginal=False, removestops=True,
                start_pos=0, start_char=0, mode='', **kwargs):
        t = Token(positions, chars, removestops=removestops, mode=mode, **kwargs)
        seglist = jieba.cut(value, cut_all=True)
        for w in seglist:
            t.original = t.text = w
            t.boost = 1.0
            if positions:
                t.pos = start_pos + value.find(w)
            if chars:
                t.startchar = start_char + value.find(w)
                t.endchar = start_char + value.find(w) + len(w)
            yield t

def ChineseAnalyzer():
    return ChineseTokenizer()

Copy the whoosh_backend.py file and change to whoosh_cn_backend.py 

 cp  whoosh_backend.py whoosh_cn_backend.py

Open the copied new file, introduce the Chinese analysis class, and use jieba word segmentation internally 

from .ChineseAnalyzer import ChineseAnalyzer

Open the copied new file, find analyzer=field_class.analyzer or StemmingAnalyzer() and change it to analyzer=field_class.analyzer or ChineseAnalyzer()

 create database

Enter the database to execute

CREATE DATABASE fresh_everyday DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_bin

Modify the database link in the project file to point to  settings.py  corresponding to your own host, port, user name, and password

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'fresh_everyday',
        'HOST':'',
        'PORT':'',
        'USER':'',
        'PASSWORD':'',
        'OPTIONS': {
            "init_command": "SET foreign_key_checks = 0;" # 关闭外键约束
        }
    }
}

Delete the xxxx_initial.py file in the migrations directory of each application in the project directory , such as /root/fresh-everyday/goods/migrations/0001_initial.py

After deletion, enter /root/fresh-everyday to perform migration

python manage.py makemigrations
python manage.py migrate

 Import data: Pass the https://github.com/lang1427/py_fresh-everyday/dailyfresh.sql file to the /root/fresh-everyday directory on the server. After connecting to the database, select the fresh_everyday database (use fresh_everyday), and pass source dailyfresh.sql; command to import data

Configure your own mailbox rule  settings.py

    # 邮箱配置
    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_HOST = 'smtp.qq.com'
    EMAIL_PORT = 587
    EMAIL_HOST_USER = '' # 发送者邮箱
    EMAIL_HOST_PASSWORD = '' # 授权码

You can go to Netease mailbox to set up SMTP service or other mailboxes

The port number can be Baidu, NetEase is 25

 uwsgi + nginx build service

  uwsgi + nginx to build a reverse proxy principle can refer to: Nginx reverse proxy

The installation of nginx can refer to: Install Nginx

uwsgi installation (I installed it in the /root directory)

pip3 install uwsgi

uwsgi configuration

  • When deploying the project, you need to set  the settings.py  folderDEBUG=False,ALLOWED_HOSTS=['*']

 uwsgi.ini configuration file (in /root/fresh-everyday directory)

Note (#Here is modified according to your actual situation)

[uwsgi]
# 指定IP端口,ip为内网ip,如果是云服务器,是云服务器内网ip
# http可以直接访问,socket是让Nginx指定的
#此处根据你的实际情况修改.
#单独用uwsgi的话把socket改成http
socket = 127.0.0.1:8001
# 项目目录,和manage.py同级的目录
#此处根据你的实际情况修改
chdir = /root/fresh-everyday
# 启动主进程,来管理其他进程
# 其它的uwsgi进程都是这个master进程的子进程
# 如果kill这个master进程,相当于重启所有的uwsgi进程
master = true
# 加载一个WSGI模块,这里加载wsgi.py这个模块
# 通常是在<django项目>/<和项目同名文件夹>/wsgi.py
# 但是如果chdir指定了项目绝对路径,只需要写<和项目同名文件夹>/wsgi.py
#此处根据你的实际情况修改
#module = /root/fresh-everyday/app/wsgi.py
#项目中wsgi.py文件的目录,相对于项目目录
#此处根据你的实际情况修改
wsgi-file=/root/fresh-everyday/app/wsgi.py
# 启动多少个进程,和核心数一样就行
processes = 1
# 每个进程最大的请求数
max_requests = 1000
# 运行的日志,通常放在 uwsgi_config 下
daemonize = /root/fresh-everyday/uwsgi_config/run.log
## 自动移除unix Socket和pid文件当服务停止的时候
vacuum = true
# 如果使用的是虚拟环境, 需要指定 pythonpath
# 如果是激活的是虚拟环境,使用命令:pip show django|grep -i location 即可得到
pythonpath = /home/python/virtualenvs/fresh_everyday/lib/python3.9/site-packages
# 指定pid文件,用于重启和停止,通常放在 uwsgi_config 下
pidfile = /root/fresh-everyday/uwsgi_config/uwsgi.pid
# 启用线程
enable-threads = true
#设置在平滑的重启(直到接收到的请求处理完才重启)一个工作子进程中,
# 等待这个工作结束的最长秒数。这个配置会使在平滑地重启工作子进程中,
# 如果工作进程结束时间超过了8秒就会被强行结束(忽略之前已经接收到的请求而直接结束)
reload-mercy = 8
#设置虚拟环境的路径
#virtualenv=/root/home/python/virtualenvs/fresh_everyday  # 修改点

Find the uwsgi execution location and establish a soft link

find / -name uwsgi

ln -s /usr/local/python39/bin/uwsgi /usr/bin/uwsgi

Start and stop uwsgi (this command is executed in the /root/fresh-everyday directory)

Start: uwsgi --ini configuration file path

uwsgi --ini uwsgi.ini

 use after startup

ps -ef | grep uwsgi

Check if (process id) is started successfully

If the above prompt appears, the startup is successful 

If the startup is unsuccessful, it is probably a problem with the uwsgi --ini configuration file

Check and modify the uwsgi --ini configuration file

Test whether uwsgi is successful 

Create a new uwsgi_test.pyfile with the following contents

def application(env,start_response):
    start_response('200 OK',[('Content-Type','text/html')])
    return [b"hello,uwsgi"]

Execute command (under virtual environment)

uwsgi --http :8003 --wsgi-file uwsgi_test.py

Results of the

browser accesshttp://127.0.0.1:8003,如下即是成功

Stop: don't stop here

uwsgi --stop uwsgi.pid

restart:

uwsgi --reload uwsgi/uwsgi.pid

If an error is reported when restarting or stopping the uwsgi servicesignal_pidfile()/kill(): No such process [core/uwsgi.c line 1693] 

  • Find the uwsgi.ini configuration file
  • Change the id (number) in the pid file to the actual process id, such as: 37693
  • Re-execute the command to restart the service

To use nginx, you need to change the http form in the uwsgi.ini configuration file to socket form, and restart uwsgi

Configure to collect static files

        Set in settings.py: STATIC_ROOT='Collected static file path'

For example: STATIC_ROOT='/var/www/fresh_everyday/static' ( manually added )
        The command for django to collect static files: python3 manage.py collectstatic Executing this command will collect the static files used in the project into the directory specified by STATIC_ROOT

 Modify the configuration file to add nginx (under the directory /usr/local/nginx/conf)

If you don't know where you can use the command to find

find / -name nginx

vim nginx.conf
 server {
        listen       8000;//     #nginx代理服务器监听8000端口
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
           #proxy_pass http://127.0.0.1:3000;#如果安装node.js则用这个,这里不用
            uwsgi_pass 127.0.0.1:8001;     #uwsgi服务器端口,跟uwsgi.ini里面配置的一样
            #root   html;
            include /root/fresh-everyday/uwsgi_config/uwsgi_params;    #uwsgi_params文件地址,默认在//usr/local/nginx/conf,这里我更改了
            #index  index.html index.htm;
        }




        # 配置静态文件目录
        # 需要迁移静态文件,上述已经写过
        location /static {
            alias /root/fresh-everyday/static;
        }

Restart nginx (under the directory /usr/local/nginx/sbin)

 ./nginx -s reload 

 The cloud server opens the port in the nginx server, which is 8000; you can access the project through the server ip:8000

But the configuration is a bit different, you can refer to this article for details: Portal

If we do not have a cloud server here, enter 127.0.0.1:8000/user/login to access

If there is any problem with the operation, you can see the operation log run.log (here I put it in the /root/fresh-everyday/uwsgi_config directory) and then solve it by yourself

 The project is probably built to this point, and there may be some bugs that need to be improved

Guess you like

Origin blog.csdn.net/weixin_55988897/article/details/128713556