[笔记] Linux 下部署 Django 环境

教程来自腾讯云大学

安装基础环境

安装 Nginx

在本教程中,我们使用 Nginx 作为 Web 服务器。

执行如下命令来安装 nginx

yum install nginx

安装完成后,执行如下命令来启动 Nginx

systemctl start nginx.service
systemctl enable nginx.service

安装 Python 环境

本实验以 Python 最新版 , Python 3.6 为基础开发。

首先,我们来安装 Python 3.6

yum install https://centos7.iuscommunity.org/ius-release.rpm -y 
yum install python36u  -y
yum install python36u-pip python36u-devel  -y

配置 Python PIP 的清华镜像

为了提升依赖的下载速度,这里我们使用清华提供的镜像源

首先,我们来创建文件夹,用于存储我们的配置文件

mkdir ~/.config/pip/

然后在文件内添加如下代码

示例代码:/root/.config/pip/pip.conf
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple

安装 MySQL

首先,我们来安装 MySQL ,这里我们使用的是 MySQL 的一个发行版 —— MariaDB 。

yum install mariadb mariadb-server -y 
systemctl start mariadb.service
systemctl enable mariadb.service

安装完成后,执行如下命令来进行 mariadb 的初始化,并根据提示设置 root 的密码(默认密码为空)

mysql_secure_installation

初始化 Python 项目

初始化虚拟环境

为了不影响外界环境的清洁,所以我们使用虚拟环境来配置 Django 项目

cd /home/
mkdir django
cd django
python3.6 -m venv venv

创建完成后,执行命令,进入虚拟环境

source venv/bin/activate

然后在虚拟环境中安装 django 并初始化项目

pip install django
django-admin startproject my
cd my 
python manage.py startapp mine

预览项目

创建完成 App 后,我们需要修改 my/settings.py 使 Django 能处理来做所有域名中的请求

示例代码:/home/django/my/my/settings.py
"""
Django settings for my project.

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

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

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

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^p3prd2a*$y-#n%jy2#@)setwu(1+yv#2kas4l*4r5_ss&+3zm'

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

ALLOWED_HOSTS = ['*']


# Application definition

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

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 = 'my.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 = 'my.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.0/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/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

修改完成后,执行如下命令来启动 Django 的测试服务器。

python /home/django/my/manage.py runserver 0.0.0.0:80

这时,你可以访问 http://<您的 CVM IP 地址> 查看预览界面

配置 Uwsgi

安装 Uwsgi

执行如下命令,退出虚拟环境。

deactivate

接下来,我们来安装配置 Uwsgi

yum install gcc -y
python3.6 -m pip install uwsgi
测试 Uwsgi

执行如下命令,测试使用 uwsgi 来启动 django

uwsgi --http :80 --chdir /home/django/my --home=/home/django/venv --module my.wsgi

此时,你可以访问 https://<您的 CVM IP 地址> ,确认是否可以查看到 django 的测试页面。

可以看到后,按下 Ctrl + C ,退出 uwsgi 进程。接下来我们来配置 Uwsgi。

配置 Uwsgi

首先,我们来创建一个目录用于存放 Django 的配置文件

mkdir -p /home/django_conf

然后在这个目录下创建一个文件 uwsgi.ini

示例代码:/home/django_conf/uwsgi.ini
[uwsgi]
socket = /home/django_conf/my.sock
chdir = /home/django/my
wsgi-file = my/wsgi.py
plugins = python
virtualenv = /home/django/venv/
processes = 2
threads = 4
chmod-socket = 664
chown-socket = nginx:nginx
vacuum = true

这里的 nginx:nginx 是 nginx 自己的用户组和用户名

配置 Nginx

配置完成 Uwsgi 后,我们来创建 Nginx 的配置文件(/etc/nginx/conf.d/my.conf)

示例代码:/etc/nginx/conf.d/my.conf
server {
    listen      80;
    server_name <您的 CVM IP 地址>;
    charset     utf-8;

    client_max_body_size 75M;

    location /media  {
        alias /home/django/my/media;
    }

    location /static {
        alias /home/django/my/static;
    }

    location / {
        uwsgi_pass  unix:///home/django_conf/my.sock;
        include     /etc/nginx/uwsgi_params;
    }
}

然后,重启 Nginx

systemctl restart nginx.service

配置 Supervisord

接下来,我们来配置 Supervisord ,确保我们的 django 可以持久运行

首先,我们要安装 pip ,用来安装 Supervisord。

yum install python-pip -y

安装完成后,我们使用 pip 来安装 supervisord,并输出配置文件

python -m pip install supervisor
echo_supervisord_conf > /etc/supervisord.conf

并在配置文件(/etc/supervisord.conf)底部添加如下代码

[program:my]
command=/usr/bin/uwsgi --ini /home/django_conf/uwsgi.ini
directory=/home/django/my
startsecs=0
stopwaitsecs=0
autostart=true
autorestart=true

添加完成后,执行如下命令来启动 supervisord

supervisord -c /etc/supervisord.conf

这时,你可以访问 http://<您的 CVM IP 地址> 查看网站

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值