CentOS6.3部署Django+Python3+Apache+Mod_wsgi

  1. 系统环境安装python3.6.5【安装位置根据个人习惯安装,我安装在root下】

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

  1. 解压

tar -zxvf Python-3.6.5.tgz

3、进入解压目录:

cd Python-3.6.5

4、编译安装【--enable-shared很总要,开启共享包依赖】

./configure --prefix=/usr/local --enable-shared

Make

Make install

5、创建python3软连接

ln -s /usr/local/bin/python3.6 /usr/bin/python3

6、还提示有包没有安装

cd Python-3.6.5

cp 没有的包 /usr/local/lib64/

cp 没有的包 /usr/lib/

cp 没有的包 /usr/lib64/

 

7系统环境没有pip,安装pip【千万不要给pip升级到18.1,会报错】

sudo yum -y install epel-release

sudo yum -y install python-pip

8、安装完检查

Python出来是系统默认的2.6

Python3是装好的3.6

创建Python虚拟环境,安装项目所需的依赖包

Python3 -m venv /home/myvenv

Cd /home/myvenv/bin

Source activate【进入虚拟环境,接下来一切操作都在虚拟环境里】

  1. 可给pip进行更新操作

Pip install upgrade pip

  1. 安装Django、gcc、mysql

Pip install Django==1.11.12

pip install gcc

yum install mysql-server

yum install mysql-devel

yum install MySQL-Python

  1. 配置mysql开机自启动

chkconfig mysqld on

4、给当前登录用户设置密码、

SET PASSWORD = PASSWORD("newpassword");

5、创建用户及设置权限

CREATE USER 'dog'@'localhost' IDENTIFIED BY '123456';

GRANT ALL ON *.* TO 'pig'@'%';

6、用新用户登录创建数据库

Mysql -u pig -p

Create database databasename;

安装apache和mod-wsgi

1.安装httpd(apache2.4)

yum install httpd
yum install httpd-devel
运行测试,需保证端口不被占用
/sbin/service httpd start
  1. 配置apache自启动

chkconfig httpd on

  1. 安装mod-wsgi

Wget https://github.com/GrahamDumpleton/mod_wsgi/archive/4.6.4.tar.gz

tar xvfz 4.6.4.tar.gz
cd mod_wsgi-4.6.4/
./configure --with-python=/usr/bin/python3
make
make install
  1. 将模块加载到apache
vim /etc/httpd/conf/httpd.conf
在LoadModule部分追加一行
LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so
  1. 重启apache服务
/sbin/service httpd restart
6、浏览器查看IP:端口会出来apache的首页

开放80端口,服务器设置安全组的入规则

关闭防火墙

克隆项目及恢复数据库

先下载git

1、wget https://www.kernel.org/pub/software/scm/git/git-1.8.2.3.tar.gz

2、yum -y install libcurl-devel expat-devel curl-devel  gettext-devel openssl-devel zlib-devel

3、yum -y install  gcc perl-ExtUtils-MakeMaker

4、tar zxf git-1.8.2.3.tar.gz cd git-1.8.2.3

5、make prefix=/usr/local/git all

make prefix=/usr/local/git install

6、#添加git到环境变量

echo "export PATH=$PATH:/usr/local/git/bin" >> /etc/bashrc

source /etc/bashrc

7、Git clone 链接·

8、恢复数据库

mysql -D database -u -p < backup.sql

9、下载requiremen.txt里面的包

pip install -i https://pypi.douban.com/simple -r requirements.txt

10、配置文件及静态文件夹:

项目位置:/home/egu_website_project/ egu_website_project

将media文件夹放在/home/egu_website_project/下面

将settings.py放在/home/egu_website_project/ egu_website_project/下面

将egu_website.conf放在/etc/httpd/conf.d/下面

将wsgi.py放在/home/egu_website_project/ egu_website_project/下面

配置如下:

"""

WSGI config for egu_website_project project.

 

It exposes the WSGI callable as a module-level variable named ``application``.

 

For more information on this file, see

https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/

"""

 

import os

 

import sys

 

from django.core.wsgi import get_wsgi_application

 

# sys.path.append('/root/.pyenv/versions/env_egu_website')

 

PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

if PROJECT_DIR not in sys.path:

    sys.path.insert(0, PROJECT_DIR)

 

os.environ["DJANGO_SETTINGS_MODULE"] = "egu_website_project.settings"

 

# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "egu_website_project.settings")

 

application = get_wsgi_application()

 

修改settings.py文件里面DEBUG=True

代码如下:

"""

Django settings for egu_website_project project.

 

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

 

For more information on this file, see

https://docs.djangoproject.com/en/1.11/topics/settings/

 

For the full list of settings and their values, see

https://docs.djangoproject.com/en/1.11/ref/settings/

"""

 

import os

import sys

import datetime

 

# 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, BASE_DIR)

sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))

sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))

 

# Quick-start development settings - unsuitable for production

# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

 

# SECURITY WARNING: keep the secret key used in production secret!

SECRET_KEY = 'c)##c@il6lru@xz%_iu$h__!s@0c(i)ww3$96oj80df^+ag%8y'

 

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

# DEBUG = True

DEBUG = True

 

ALLOWED_HOSTS = ['*']

 

AUTH_USER_MODEL = 'users.UserProfile'

# Application definition

 

INSTALLED_APPS = [

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

 

    'users.apps.UsersConfig',

    'DjangoUeditor',

    'crispy_forms',

    'django_filters',

    'xadmin',

    'reversion',

    'rest_framework',

    'rest_framework.authtoken',

    'corsheaders',

 

    'common.apps.CommonConfig',

    'home.apps.HomeConfig',

    'activity.apps.ActivityConfig',

    'investment.apps.InvestmentConfig',

    'partner.apps.PartnerConfig',

    'space.apps.SpaceConfig',

    'think_tank.apps.ThinkTankConfig',

    'wechat.apps.WechatConfig',

    'recruitment.apps.RecruitmentConfig',

 

    'mod_wsgi.server',

]

 

MIDDLEWARE = [

    'corsheaders.middleware.CorsMiddleware',

    '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',

    'django.middleware.gzip.GZipMiddleware',

]

 

CORS_ORIGIN_ALLOW_ALL = True

 

ROOT_URLCONF = 'egu_website_project.urls'

 

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',

            ],

        },

    },

]

 

WSGI_APPLICATION = 'egu_website_project.wsgi.application'

 

# Database

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

 

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': "egu_website_database",

        'USER': 'egu',

        'PASSWORD': "egu05231931.",

        'HOST': "127.0.0.1",

        'OPTIONS': {'init_command': 'SET storage_engine=INNODB;SET foreign_key_checks = 0;'}

    }

}

 

# DATABASES = {

#     'default': {

#         'ENGINE': 'django.db.backends.sqlite3',

#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

#     }

# }

 

 

# Password validation

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

 

# 设置时区

# LANGUAGE_CODE = 'en-us'

LANGUAGE_CODE = 'zh-hans'  # 中文支持,django1.8以后支持;1.8以前是zh-cn

 

# TIME_ZONE = 'UTC'

TIME_ZONE = 'Asia/Shanghai'

 

USE_I18N = True

 

USE_L10N = True

 

# USE_TZ = True

USE_TZ = False  # 默认是Ture,时间是utc时间,由于我们要用本地时间,所用手动修改为false!!!!

 

# Static files (CSS, JavaScript, Images)

# https://docs.djangoproject.com/en/1.11/howto/static-files/

 

STATIC_URL = '/static/'

 

STATICFILES_DIRS = (

    os.path.join(BASE_DIR, "templates/static"),

)

 

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

 

MEDIA_URL = "/media/"

 

MEDIA_ROOT = os.path.join(BASE_DIR, "media")

 

REST_FRAMEWORK = {

    #'DEFAULT_PERMISSION_CLASSES': (

#     'rest_framework.permissions.IsAuthenticated',

#    ),

    'DEFAULT_AUTHENTICATION_CLASSES': (

       'rest_framework_jwt.authentication.JSONWebTokenAuthentication',

        'rest_framework.authentication.BasicAuthentication',

        'rest_framework.authentication.SessionAuthentication',

    ),

    'DEFAULT_PARSER_CLASSES': (

        'rest_framework.parsers.JSONParser',

        'rest_framework.parsers.FormParser',

        'rest_framework.parsers.MultiPartParser',

        # 'rest_framework.parsers.FileUploadParser'

    ),

 

    # 'DEFAULT_THROTTLE_CLASSES': (

    #     'rest_framework.throttling.AnonRateThrottle',

    #     'rest_framework.throttling.UserRateThrottle'

    # ),

    # 'DEFAULT_THROTTLE_RATES': {

    #     'anon': '2/minute',

    #     'user': '3/minute'

    # }

}

 

UEDITOR_SETTINGS = {

    'config': {

        "toolbars": [['source', '|', 'undo', 'redo', '|',

                      'bold', 'italic', 'underline', 'formatmatch', 'autotypeset', '|',

                      'forecolor', 'backcolor', '|',

                      'link', 'unlink']]

    },

    'upload': {

        # 'imageManagerListPath': '',

        # 'imageUrlPrefix': 'http://0.0.0.0:8000'

        # 'imageUrlPrefix': 'http://192.168.0.25:8000'

        'imageUrlPrefix': 'http://118.190.177.7'

    }

}

 

# 亿美软通短信平台设置

YIMEI_SETTINGS = {

    'cdkey': '8SDK-EMY-6699-RIVTL',

    'password': '101010',  # 正确

    # 'password': '101011',

    # 'regex_error': r'<error>(.+?)</error>',

    'debug': {

        # 'state': True,

        'state': False,

        'response': True

    }

}

 

# 正则表达式

REGEX = {

    'phone': '^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$',

    'all_phone': '^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$',

    'password': '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,}$',

    'username': '^[\u4e00-\u9fff\w\-]{2,20}$',

    'first_name': '^[\u4e00-\u9fffA-Za-z]{0,10}$',

}

# 验证错误信息

VALIDATE_ERRORS = {

    'username': {

        'null': '用户名不能为空@.@',

        'regex': '用户名格式不对,长度必须在2到20且仅包含中文字母数字-_'

    },

    'phone': {

        'null': '手机号码不能为空@.@',

        'regex': '手机号码格式不对,请输入正确的手机号码@.@'

    },

    'password': {

        'null': '密码不能为空@.@',

        'regex': '密码长度必须不少于8位,且必须包含数字和字母@.@'

    },

    'first_name': {

        'regex': '真实姓名格式不对,必须不大于10位且只包含中文字母@.@'

    }

}

 

JWT_AUTH = {

    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),

    'JWT_AUTH_HEADER_PREFIX': 'JWT',

}

 

AUTHENTICATION_BACKENDS = (

    'users.views.CustomBackend',

)

 

此时运行python manage.py runserver o.o.o.o:8000可以出来项目前端页面

 

Apache配置文件

两个位置:

/etc/httpd/conf/httpd.conf

/etc/httpd/conf.d/egu_website.conf

httpd.conf文件没有需要特别修改的

egu_website.conf配置如下:

 

# WSGIPythonHome "/root/.pyenv/versions/egu-website-py3.6.4"

#WSGIPythonHome "/root/.pyenv/versions/3.6.4/envs/egu-website-py3.6.4"

# WSGIPythonPath /:/var/www/html/ENV/lib/python2.7/site-packages:/var/www/html/wsgi

# WSGIPythonPath /home/egu_website_project:/root/.pyenv/versions/3.6.4/envs/env-egu-website/lib/python3.6/site-packages

 

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

 

#LoadModule wsgi_module "/home/env3-egu-website/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so"

WSGIPythonHome "/home/myvenv"

 

 

# listen 8000

<VirtualHost *:80>

    ServerName webtest.egu360.com

    ServerAlias webtest.egu360.com

    # ServerAdmin yangdy@egu360.com

 

    Alias /media/ /home/egu_website_project/media/

    Alias /static/ /home/egu_website_project/static/

 

    <Directory /home/egu_website_project/media>

         # Require all granted

       Order deny,allow

       Allow from all

    </Directory>

 

    <Directory /home/egu_website_project/templates/static>

        # Require all granted

       Order deny,allow

       Allow from all

    </Directory>

 

    WSGIScriptAlias / /home/egu_website_project/egu_website_project/wsgi.py

    # WSGIPythonPath /home/egu_website_project:/root/.pyenv/versions/env-egu-website

    # WSGIDaemonProcess egu360.com python-path=/home/egu_website_project:/root/.pyenv/versions/egu-website-py3.6.4/lib/python3.6/site-packages

    #  WSGIDaemonProcess egu360.com python-path=/root/.pyenv/versions/3.6.4/envs/egu-website-py3.6.4/lib/python3.6/site-packages

    # WSGIProcessGroup egu360.com

 

    <Directory /home/egu_website_project/egu_website_project>

    <Files wsgi.py>

        # Require all granted

       Order deny,allow

       Allow from all

    </Files>

    </Directory>

</VirtualHost>

 

修改项目属主和权限

chmod -R 755 /home/egu_website_project/ egu_website_project

# chown -R apache:apache /home/egu_website_project/ egu_website_project

访问域名可以看到项目已经运行起来

问题记录

  1. mysql表的字符集错误,在数据类型为varchar的字段添加中文,发现数据库里面存的是问号。

原因:mysql安装完,、etc/my.cnf配置文件没有设置默认字符集,所以表在django初始建表时是lantin1,不是utf8,需要修改下表的字符集设置。

查看表的字符集

Show  create table 表名

1.1修改表的默认字符集设置

alter table 表名 default character set utf8;

alter table activity_vote modify rule longtext  character set utf8;

1.2修改配置文件,这样以后在创建时就是utf8了。

如下配置:

1.3进入mysql,查看字符集

Show variable like ‘%char%’;

  1. 华为云服务器ssh远程连接,不操作10分钟左右就自己断了。

原因:这是系统处于安全的配置,先要修改,步骤如下:

2.1远程连接服务器,修改/etc/profile

Vim /etc/profile

修改链接时间

export TMOUT=32400

代表允许链接9个小时

  1. 上传图片文件夹没有权限的问题

原因:没有给media文件夹赋权

打开/etc/httpd/conf/httpd.conf

查看user、group组拥有者,我的是apache

给/home/egu*/egu*/media文件赋权:

Chgrp -R apache media/

Chgrp -R g+w media/

重启apache服务

Service httpd restart

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值