Centos7下Django 3.2.8安装及静态文件目录配置(python3+sqlite3.36+uwsgi+nginx)

本文详细介绍了如何在CentOS7上安装Python3、Django3.2.8、SQLite3.36,并解决Django与新SQLite版本的兼容问题。然后,通过uwsgi配置部署Django应用,解决uwsgi无法识别LD_LIBRARY_PATH的问题。最后,部署nginx并配置静态文件处理,确保应用能够正常运行。
摘要由CSDN通过智能技术生成

(声明:本文以下内容通过网络搜索结果进行整理,仅供参考。)

一、python3安装

​1、安装python版本说明
Django3.2.8对应的Python版本请参照官网
https://docs.djangoproject.com/zh-hans/3.2/faq/install/#faq-python-version-support
2、使用阿里云yum repo 
http://mirrors.aliyun.com/repo/
将Centos-7.repo和epel-7.repo下载至/etc/yum.repos.d/目录下
说明:EPEL的全称叫 Extra Packages for Enterprise Linux
执行yum clean all以及yum makecache,更新yum缓存
3、安装python3
yum list python3 查询是否存在python3的相关安装包
yum install -y python3 python3-devel安装
注意:python3-devel 还是要安装一下的,否则有可能会出现各种意想不到的问题。
更新pip3   
pip3 install --upgrade pip

二、Django 3.2.8安装

pip3 install Django == 3.2.8

查看安装版本 python3 -m django --version

-m mod run library module as a script (terminates option list)
"mod"是“module”的缩写,即“-m”选项后面的内容是 module(模块),其作用是把模块当成脚本来运行。“terminates option list”意味着“-m”之后的其它选项不起作用,在这点上它跟“-c”是一样的,都是“终极选项”。官方把它们定义为“接口选项”(Interface options),需要区别于其它的普通选项或通用选项。​

三、Sqlite3.36安装

Centos7系统自带的sqlite3版本较低,Django3.2.8需要sqlite3.9及以上版本支持

访问 https://www.sqlite.org/   下载 sqlite-autoconf-3360000.tar.gz

说明:C source code as an amalgamation. Also includes a "configure" script and TEA makefiles for the TCL Interface.

# ./configure --prefix=/usr/local/sqlite

说明:/usr/local/相当于win系统program file文件夹

# make && make install

# /usr/local/sqlite/bin/sqlite3 --version

替换老的/usr/bin/sqlite3

mv /usr/bin/sqlite3 /usr/bin/sqlite3_old
ln -s /usr/local/bin/sqlite3 /usr/bin/sqlite3

链接库文件为 /usr/local/lib/libsqlite3.so

下面uwsgi报错SQLite 3.9.0 or later is required (found 3.7.17)会用到

将路径传递给共享库,设置开机自启动执行,可以将已下内容写到~/.bashrc尾部

#Add for Django sqlite3.36
LD_LIBRARY_PATH="/usr/local/lib":$LD_LIBRARY_PATH
export LD_LIBRARY_PATH

如果如果你想立即生效,可以执行source 〜/.bashrc 将在每次启动终端时执行

可以新建文件uwsgi.sh,保存到/etc/profile.d/,对所有用户生效,配置内容如下:

#set sqlite3.36 environment
LD_LIBRARY_PATH="/usr/local/lib":$LD_LIBRARY_PATH
export LD_LIBRARY_PATH


四、uwsgi安装及配置

请参考djangoproject官方网站“部署 Django”部分

安装yum install -y uwsgi

将uwsgi.ini配置文件放置在django project 目录下

以下为uwsgi参考配置,如果没有nginx,可以不配置socket,可以同时配置http和socket,不影响应用的访问,但是对于Django的静态文件访问有影响。

[uwsgi]

#Server Port
http = :8080

#Specify how to communicate with nginx,without affecting the operation of uwsgi itself.
#If need to access Django by nginx,please configure the nginx.conf.
socket = ip:8000

# start a master process to manage the remaining child processes.
master = True
processes = 4
threads = 2

#Please user absolute path of Python virtual enviroment directory.
#if so,"home" is the root directory of the virtual enviroment and 
#PYTHONHOME is the bin directory of the virtual enviroment(where Python executable files are placed)
# home = /env
# PYTHONHOME = /env/bin

#Django project directory,at the same level directory as manage.py.
chdir = /path/to/your/project




#Automatically remove the UNIX Socket and PID fileS when the service stops.
vacuum = True

#The wsgi in the main application of the django project.
#The following configuration is valid when running uwsgi under the Django root directory.
#The main application name is the directory name with setting.py.
#If running in another directory,it is recommended to writen an absolute path below.
# wsgi-file = /path/to/your/project/wsgi.py
# wsgi-file = project/wsgi.py
#
#If have configured the wsgi-file ,don't configure the module.
#
#load a WSGI module.For example,load mysite/wsgi.py here.
module=mysite.wsgi:application


#Save the PID of the main process to control the uwsgi service.
pidfile = /tmp/project-master.pid

#Set maximum limit for each worker process to process requests.
#When the maximum limit is reached,the process will be recycled(restarted)to prevent memory leakage.
max-requests=5000

#Set background running to save log.Once daemonize is configured,uwsgi will run in the 
#background and output logs to the specified directory.
daemonize=/var/log/uwsgi/mysite.log

#Static files map.Absolute path of static directory under Django Project.
# static-map = /your/django/project/static

运行:uwsgi --ini uwsgi.ini

运行后,系统会报错

访问http://ip:8080/ 网页会出现如下错误提示

Internal Server Error

请查看/var/log/uwsgi/mysite.log(访问日志)

.................

 File "/usr/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 69, in check_sqlite_version
    'SQLite 3.9.0 or later is required (found %s).' % Database.sqlite_version
django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17).

也就是/usr/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py这个文件引起的错误

from sqlite3 import dbapi2 as Database

def check_sqlite_version():
    if Database.sqlite_version_info < (3, 9, 0):
        raise ImproperlyConfigured(
            'SQLite 3.9.0 or later is required (found %s).' % Database.sqlite_version
        )


check_sqlite_version()

Django接口模块还是不能识别到系统已将sqlite3.7升级到sqlite3.36,通过linux运行python3互动模式,显示是正常的。

Python 3.6.8 (default, Nov 16 2020, 16:55:22) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sqlite3 import dbapi2 as Database
>>> Database.sqlite_version_info
(3, 36, 0)

python3 manage.py runserver 0.0.0.0:8080 --insecure

能正常访问http://ip:8080/admin

程序能正常运行

对于uwsgi的问题,解决uwsgi不能识别LD_LIBRARY_PATH变量,因为uwsgi通过如下配置访问django project wsgi

chdir = /your/project

module = mysite.wsgi:application

调用的是

/usr/lib64/libsqlite3.so.0
/usr/lib64/libsqlite3.so.0.8.6

这是因为安装sqlite3.36时候指定路径为/usr/local/lib,所以在uwsgi模式运行的django不能找到升级后的sqlite3的库文件(也许以服务模式运行的程序不能依赖环境变量

通过find / -name libsqlite3* 查找有如下结果
/usr/local/lib/libsqlite3.so.0.8.6
/usr/local/lib/libsqlite3.so.0
/usr/local/lib/libsqlite3.so

将/usr/local/lib/libsqlite3.so.0.8.6指向/usr/lib64/libsqlite3.so.0

mv /usr/lib64/libsqlite3.so.0 /usr/lib64/libsqlite3.so.0_old

ln -s /usr/local/lib/libsqlite3.so.0.8.6 /usr/lib64/libsqlite3.so.0

五、部署nginx及配置

yum install -y nginx

配置文件如下:

在/etc/nginx/conf.d/新建django_project.conf文件,将default.conf修改为default.conf.bak

server {
    listen       80;
    server_name  ip;	
	
    #charset koi8-r;
	charset utf-8;
	
    #access_log  /var/log/nginx/host.access.log  main;
	access_log  /var/log/nginx/host.access.log;
	
    location / {
        #root   /usr/share/nginx/html;
        #index  index.html index.htm;
		
		include uwsgi_params;
        #socket port to uwsgi socket,must the same port
		uwsgi_pass ip:8000;
    }
	
	#Django static file
	location /static {
		alias /var/www/html/mysite/static/;
	}
	
	
    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

六、收集djang static文件到nginx中的location /static文件夹下

在执行 python manage.py collectstatic 命令之前,请在项目的setting.py增加如下设置

#When DEBUG is set to True,STATIC_URL will work.
STATIC_URL = '/static/'

#When DEBUG is set to False,STATIC_ROOT will work.
STATIC_ROOT = '/var/www/html/rjdjsite/static/'

#python3 manage.py collectstatic the static directory under the project to STATIC_ROOT 
STATICFILES_DIRS = [ BASE_DIR / "static",]

完整的参考配置如下:

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 3.2.8.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=2gep%)eg8a8^dnab2i505r$da^zru&bofdw7(0ccdne8w@c^6'

# SECURITY WARNING: don't run with debug turned on in production!
#DEBUG = True
DEBUG = False

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rjzwwdj.apps.MysiteConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

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


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

#LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'


#TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

#When DEBUG is set to True,STATIC_URL will work.
STATIC_URL = '/static/'

#When DEBUG is set to False,STATIC_ROOT will work.
STATIC_ROOT = '/var/www/html/mysite/static/'

#python3 manage.py collectstatic the static directory under the project to STATIC_ROOT 
STATICFILES_DIRS = [ BASE_DIR / "static",]


# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

--- the end---

(整理于2021年10月9日)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值