Django项目部署(阿里云linux服务器Centos7.6 2核2G)

7 篇文章 0 订阅
1 篇文章 0 订阅

一、安装python3.7
二、把相关django项目拷贝到linux服务器
三、安装django相关依赖
(1)pip3 install django==2.2.12
(2)安装mysqlclient(确保已安装mysql,见下文)
若pip3 install mysqlclient执行报错,先执行yum install mysql-devel
(3)若项目的models.py文件在服务器上有改动,cd切换到manage.py同名目录下,先 执行 python3 manage.py makemigrations生成数据库迁移文件,再执行数据库迁移 命令python3 manage.py migrate。
(4)在linux服务器上新建文件夹
STATIC_ROOT = ‘/code/mysite7_static/static’
cd 切换到manage.py所在目录,执行python3 manage.py collectstatic 生成admin 所需的静态资源文件,不然admin缺失样式
(5)settings.py配置问题(见附录)
主要配置:
DEBUG = False # 服务器关闭debug模式
ALLOWED_HOSTS = [’*’]
‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],
DATABASES = { # 数据库连接配置
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: 项目名称,
‘USER’: ‘root’,
‘PASSWORD’: ‘密码’,
‘HOST’: ‘127.0.0.1’,
‘PORT’: ‘3306’
}
}
MEDIA_ROOT = ‘/media/’ # 文件上传的目录
MEDIA_ROOT = os.path.join(BASE_DIR, ‘media’)
#静态文件夹 在linux服务器上新建文件夹
STATIC_ROOT = ‘/code/mysite7_static/static’

四、安装uwsgi
(1)使用镜像暗转uwsgi
sudo pip3 install uwsgi==2.0.18 -i https://pypi.tuna.tsinghua.edu.cn/simple/
(2)检查是否安装成功
sudo pip3 freeze|grep -i ‘uwsgi’
(3)在settins.py同名目录下新建文件uwsgi.ini
内容为:
[uwsgi]
#http=127.0.0.1:8000
socket=127.0.0.1:8000
chdir=/code/mysite7 # 项目所在目录
wsgi-file=mysite7/wsgi.py # wsgi.py 所在位置
process=2 # 进程数
threads=2 # 线程数
pidfile=uwsgi.pid
daemonize=uwsgi.log
master=True
(4)启动uwsigi
启动必须在settings的同名目录下执行,否则启动不起来
启动命令:uwsgi --ini uwsgi.ini
查看是否启动:ps aux|grep ‘uwsgi’
关闭命令: uwsgi --stop uwsgi.pid

五、安装nginx
(1)下载nginx
sudo yum install nginx
nginx位置 /etc/nginx
nginx 日志位置 /var/log/nginx
(2)启动nginx
命令行直接输入nginx即可启动,默认80
查看端口是否被占用
sudo nginx -t 检查配置文件的语法有没有问题
sudo lsof -i:80
kill -9 端口号
killall -9 nginx

注:Vim编辑文件时,键入i是插入,esc退出编辑,:wq保存退出;:wq!强制退出

(3)常用Linux命令
关闭history记录功能
set +o history
打开history记录功能
set -o history
清空记录
history -c 记录被清空,重新登录后恢复。
rm -f $HOME/.bash_history 删除记录文件,清空历史。
临时不记录
在执行的命令前添加空格。例如:history

(4)Nginx配置文件nginx.conf (见附录)
在nginx目录下找到nginx.conf nginx位置/etc/nginx
http中Sever上面加入client_max_body_size 10m;可设置上传文件的大小,niginx默认设置的较小。
Server下加入:
location /{
uwsgi_pass 127.0.0.1:8000;
include /etc/nginx/uwsgi_params;
}
location /static { # admin静态资源存放位置
alias /code/mysite7_static/static;
}
location /media { # 文件上传目录
alias /code/mysite7/media;
}

(5)

六、安装MySQL
参考:https://www.cnblogs.com/Mr-Rshare/p/11799945.html
https://www.cnblogs.com/jepson6669/p/9012019.html
Mysql 重置密码问题
安装完mysql 之后,登陆以后,不管运行任何命令,总是提示这个错误:
You must reset your password using ALTER USER statement before executing this statement
处理步骤为:依次执行下面三条代码。
SET PASSWORD = PASSWORD(‘your new password’);
ALTER USER ‘root’@‘localhost’ PASSWORD EXPIRE NEVER;
flush privileges;
这里要注意的是your new password 必须包含数字,字母包含大小写,标点符号。不然好像是不能通过的。
完成以上三步退出再登,使用新设置的密码就行了,以上除了 your new password 需要修改成新密码外,其他原样输入即可。
1.更改root密码
mysqladmin -uroot password ‘yourpassword’
2.远程登陆mysql服务器
mysql -uroot -p -h192.168.137.10 -P3306
3.查询数据库
show databases;
4.进入某个数据库
use databasename;
5.列出数据库中的表
show tables;

附录:1.settings.py
“”"
Django settings for mysite7 project.

Generated by ‘django-admin startproject’ using Django 2.2.12.

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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.2/howto/deployment/checklist/

#SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ‘’

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’,
‘upload_app’
]

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

'middleware.mymiddleware.MyMW',
# 'middleware.mymiddleware.VisitLimit',
'middleware.mymiddleware.ExceptionMW'

]

ROOT_URLCONF = ‘mysite7.urls’

TEMPLATES = [
{
‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],
# ‘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 = ‘mysite7.wsgi.application’

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

DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: ‘mysite7’,
‘USER’: ‘root’,
‘PASSWORD’: ‘’,
‘HOST’: ‘127.0.0.1’,
‘PORT’: ‘3306’
}
}

#Password validation
#https://docs.djangoproject.com/en/2.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/2.2/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.2/howto/static-files/

STATIC_URL = ‘/static/’

#数据库缓存配置 需要手动执行 创建表的命令
#python manage.py createcachetable
#python manage.py migrate

CACHES = {
‘default’: {
‘BACKEND’: ‘django.core.cache.backends.db.DatabaseCache’,
‘LOCATION’: ‘my_cache_table’,
‘TIMEOUT’: 300, # 缓存保存时间 单位秒,默认值300
‘OPTIONS’: {
‘MAX_ENTRIES’: 300, # 缓存最大数据条数
‘CULL_FREQUENCY’: 2, # 缓存条数达到最大时 删除1/x的缓存数据
}
}
}

MEDIA_ROOT = ‘/media/’
MEDIA_ROOT = os.path.join(BASE_DIR, ‘media’)

gbvyimtuaksjiaji
EMAIL_BACKEND = ‘django.core.mail.backends.smtp.EmailBackend’
EMAIL_HOST = ‘smtp.qq.com’ # 腾讯QQ邮箱 SMTP 服务器地址
EMAIL_PORT = 25 # SMTP服务器的端口号
EMAIL_HOST_USER = ‘’ # 发送邮件的QQ邮箱
EMAIL_HOST_PASSWORD = ‘’ # QQ邮箱 设置 账户 POP3/SMTP服务 开启
EMAIL_USER_TLS = False # 与SMTP服务器

#发送邮件

from django.core import mail
#>>> mail.send_mail(subject=‘测试邮件’,message=‘hahaha’, from_email=’’,recipient_list=[’’] )

EX_EMAIL = [’’]

#静态文件夹
STATIC_ROOT = ‘/code/mysite7_static/static’

==============================================================================
2.niginx.conf

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

#Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
worker_connections 1024;
}

http {
log_format main '$remote_addr - r e m o t e u s e r [ remote_user [ remoteuser[time_local] “KaTeX parse error: Double superscript at position 34: … '̲status b o d y b y t e s s e n t " body_bytes_sent " bodybytessent"http_referer” ’
‘“ h t t p u s e r a g e n t " " http_user_agent" " httpuseragent""http_x_forwarded_for”’;

access_log  /var/log/nginx/access.log  main;

sendfile            on;
tcp_nopush          on;
tcp_nodelay         on;
keepalive_timeout   65;
types_hash_max_size 4096;
client_max_body_size 10m;

include             /etc/nginx/mime.types;
default_type        application/octet-stream;


# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;

server {
    listen       80;
    listen       [::]:80;
    server_name  _;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

   location /{
        uwsgi_pass   127.0.0.1:8000;
        include  /etc/nginx/uwsgi_params;
   }

    location /static {
           alias  /code/mysite7_static/static; 
   }

    location /media {
        alias  /code/mysite7/media;
    }


    error_page 404 /404.html;
    location = /404.html {
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    }
}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值