01-nginx+uwsgi+django+qiniuyun+postgresql 建站指南

经过了一个星期的努力,终于是把自己的个人博客上线到自己的阿里云服务器上www.fortable.cn,半年前买的域名和服务器也是终于有了内容。在这期间,也经过了不少坑,现在把这些都记录下来。我将从django(zinnia)–>uwsgi+nginx–>postgresql–>qiniuyun这个顺序逐一记录。由于本人在开发的时候是使用的ubuntu16.04 64位系统。aliyun上使用的是centos7.3 64位系统。在移植的过程中还经过了不少坑,现在一一记录下来。

目录 (Table of Contents)

[TOC]

1.zinnia

本人采用的是github上比较热门的django开源项目zinnia-0.18.1,详细的使用方法查看此开源项目的官方文档。在此开发过程中发现所有项目的官方文档和程序的log日志是解决问题的终极大招。

安装virtualenv

每一个python项目最好使用独立的python环境.

pip install virtualenv                      #安装virtualenv
cd yourProPath/                             #进入你的项目目录上一级
virtualenv --no-site-packages venv          #创建一个没有其他多余安装包的干净环境,生成目录venv。
source venv/bin/activate                    #激活环境
pip install "packages"                      #安装你所需要的包,切记前面不要加sudo,否则pytho包会安装在电脑环境中
deactivate                                  #退出当前python环境

加速pip install 方法
1.proxychains pip install package; #如果电脑上安装代理可以使用官方镜像
2.pip install ‘package’ -i http://pypi.douban.com/simple –trusted-host pypi.douban.com #国内使用豆瓣镜像

注:如果windows用户出现错误: failed to compile wheel 根据提示去微软官网下载 VCforpy27.msi 安装即可

安装项目所需要的python包

所需要下载的python包配置清单已经上传至我的github空间,下载下来然后使用

pip install -r require.txt

运行zinnia

依照zinnia的官方教程,对settings.py和urls.py进行设置,然后

python manage.py migrate                        #将model数据写入数据库表中,创建数据库表
python manage.py runserver 0.0.0.0:8080         #将djano服务拉起来,即可在浏览器中看见页面
###**设置admin用户**
python manage.py createsuperuser                #按照提示输入用户名密码即可
python manage.py changepassword username        #修改用户名密码
python manage.py shell                          #进入django SHELL 界面

其他的一些功能设置可以参考官方教程。

2.Centos上利用 uwsgi+nginx部署django

在centos上安装uwsgi和nginx

安装uwsgi: pip install uwsgi
安装nginx: sudo yum install nginx

设置uwsgi和nginx

新建一个uwsgi.ini设置如下:

[uwsgi]
socket = 127.0.0.1:3316    #用端口连接nginx
#http =127.0.0.1:80
# the base directory (full path)
chdir           =/home/chongjie/service/blog/djangosite     #django目录
# Django's wsgi file
module          = djangosite.wsgi                                   
# the virtualenv (full path)
home            = /home/chongjie/service/venv
# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 10
# the socket (use the full path to be safe
#socket          = /path/to/your/project/mysite.sock                      #用socket文件连接
# ... with appropriate permissions - may be needed
# chmod-socket    = 664
# clear environment on exit
vacuum          = true
#print log file
daemonize = /var/log/uwsgi.log                           #日志文件地址,需要自己创建

vim /etc/nginx/nginx.conf 设置nginx

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user root;                    //改成root用户 不然会出现访问permission denied
worker_processes auto;
error_log /var/log/nginx/error.log;    //error log 日志 在调试的时候非常有用
pid /run/nginx.pid;

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

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$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 2048;

    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 default_server;
        listen       [::]:80 default_server;
        server_name  47.74.135.66;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
        location /static/ {
                alias /home/chongjie/service/blog/djangosite/staticfile/;      #设置为django的静态文件夹(后面讲这个文件夹怎么生成)
                }
        location / {
            uwsgi_pass  127.0.0.1:3316;            #uwsgi的对接port口
            include   uwsgi_params;                  #在/etc/nginx的目录里面的文件 uwsgi的补充协议
           # include   /etc/nginx/mime.types;
             }
            error_page 404 /404.html;
            location = /40x.html {
        }

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

然后

uwsgi uwsgi.ini
service nginx start

则配置好了对应的nginx+uwsgi.在对nginx.conf再次编辑时,可以使用nginx -t检查配置文件正确与否,如果返回ok,用 -s reload 重新加载配置文件,nginx里面一定要设置django的静态文件夹,不然网页会找不到样式

3.zinnia进阶–settings.py文件详解

下面是我的settings.py的全部内容

""
Django settings for djangosite project.

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

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

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7v2v5d3b-qqdsadmgqy8880kk)-w%b8rq(3wjmgd!bi2ye)f-lmq4'

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

ALLOWED_HOSTS = []

SITE_ID  = 2
# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django_comments',
    'mptt',
    'tagging',
    'theme',
    'zinnia_bootstrap',
    'zinnia',
    'django.contrib.sitemaps',
]

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 = 'djangosite.urls'


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
                os.path.join(BASE_DIR,'templates'),
                os.path.join(BASE_DIR,'tempaltes','zinnia'),
                ],
        'APP_DIRS': False,
        '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',
                'django.template.context_processors.i18n',
                'zinnia.context_processors.version',
            ],
            'loaders':[
                'app_namespace.Loader',
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
                ],
        },
    },
]

WSGI_APPLICATION = 'djangosite.wsgi.application'


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

DATABASES = {
    'default': {
       # 'ENGINE': 'django.db.backends.sqlite3',
       # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'ENGINE' : 'django.db.backends.postgresql_psycopg2',
        'NAME' : 'blog',
        'USER' : 'postgres',
        'PASSWORD' : '**********',
        'HOST' : '127.0.0.1',
        'PORT' : '5432',
    }
}

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

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,"staticfile/")
STATICFILES_DIRS = [os.path.join(BASE_DIR,"static"),]


#--media--qiniuyun server
QINIU_ACCESS_KEY = 'wCdL4z3ix7Zk5pKXfGHvlq8AGKLNioocpHaRd7SH'
QINIU_SECRET_KEY = 'sdF8fSoPSOKkbLbM6XETxQ4o7s3Wc9Y4fP4xg87G'
QINIU_BUCKET_NAME = 'fortable'
QINIU_BUCKET_DOMAIN = 'ot27paxji.bkt.clouddn.com/'
QINIU_SECURE_URL = False      #using http 

PREFIX_URL = 'http://'

MEDIA_URL = PREFIX_URL + QINIU_BUCKET_DOMAIN + '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

DEFAULT_FILE_STORAGE = 'qiniustorage.backends.QiniuMediaStorage'
#--media-- local server
#MEDIA_URL ='/media/'
#MEDIA_ROOT = os.path.join(BASE_DIR,'media')

ZINNIA_MARKUP_LANGUAGE = 'markdown'
ZINNIA_MARKDOWN_EXTENSIONS = ['markdown.extensions.extra',
                        'markdown.extensions.abbr',
                        'markdown.extensions.attr_list',
                        'markdown.extensions.def_list',
                        'markdown.extensions.fenced_code',
                        'markdown.extensions.footnotes',
                        'markdown.extensions.tables',
                        'markdown.extensions.smart_strong',
                        'markdown.extensions.codehilite',
                        'markdown.extensions.admonition',
                        'markdown.extensions.headerid',
                        'markdown.extensions.meta',
                        'markdown.extensions.nl2br',
                        'markdown.extensions.sane_lists',
                        'markdown.extensions.smarty',
                        'markdown.extensions.toc',
                        'markdown.extensions.wikilinks',
]

#EMAIL
#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'

# Host for sending e-mail.
EMAIL_HOST = 'smtp.qq.com'

# Port for sending e-mailt
EMAIL_PORT = '465'

# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = '****'
EMAIL_HOST_PASSWORD = '*******'
EMAIL_USE_TLS = True

EMAIL_TIMEOUT = 10
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
#EMAIL_USE_SSL = True

静态文件的设置

如果需要修改zinnia模板的对应静态图标和图片等,则需要重载静态文件或者media文件。static files和media files的设置和网页样式的自定义差不多,也是重载对应的目录,并将对应的地址注册到settings.py文件里面,具体参考django settings 官方文档 .主要settings.py设计代码如下:

#static settings
STATIC_URL = '/static/'        #和manage.py同级目录的static文件夹   
STATIC_ROOT = os.path.join(BASE_DIR,"staticfile/")        #python manage.py collectstatic 静态文件存放地址
STATICFILES_DIRS = [os.path.join(BASE_DIR,"static"),]   #在这里面加入你所需要更改的静态文件
#media settings
MEDIA_URL ='/media/'                                            #和manage.py同级目录的media文件夹
MEDIA_ROOT = os.path.join(BASE_DIR,'media')    #media文件路由地址,保存上传文件的文件夹

STATIC_ROOT:运行上边提到的命令:python manage.py collectstatic 之后静态文件将要复制到的目录,这个目录只有在运行collectstatic时候才会用到,不能想当然的以为这个目录和MEDIA_ROOT的作用是相同的,否则在开发环境的时候可能一直无法找到静态文件。
STATIC_URL:设置的static file的起始url,这个只是在template里边引用到,这个参数和MEDIA_URL的含义相同,
STATICFILES_DIRS:和TEMPLATE_DIRS的含义差不多,就是除了各个app的static目录以外还需要管理的静态文件设置,比如项目的公共文件差不多。
各个app目录下的静态文件static/django会自动找到,这个点和app下的templates目录下差不多。

网页样式的自定义

静态模板的修改,可以参考马志锋–边做边学,Python&Django实战教程-10-修改显示模板。主要是重载对应的你所所需的模板文件比如skeleton.html和base.html,并且将重载的文件夹地址写入对应 TEMPLATES.’DIRS‘里面

mail邮箱的设置

刚开始参考网上的设置,找了好久没有找到,终于找到有一个参考的答案
settings.py的设置如下:

#EMAIL
#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'  #不是用这个
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'                     #正确的用这个

# Host for sending e-mail.
EMAIL_HOST = 'smtp.qq.com'

# Port for sending e-mailt
EMAIL_PORT = '465'

# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = '****'
EMAIL_HOST_PASSWORD = '*******'
EMAIL_USE_TLS = True

EMAIL_TIMEOUT = 10
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
#EMAIL_USE_SSL = True

首先阿里云将smtp 25端口永久封死,即使你在安全策略里面将25端口打开,使用 telnet smtp.qq.com 25 或者telnet smtp.163.com 25都是ping不同的,只有使用默认的ssl 465端口。1.你需要把你的邮箱开启smtp服务,我这里使用的是QQ邮箱,将会生成一个password,将该password放置在settings.py的文件里面。2.为了使用’django_smtp_ssl.SSLEmailBackend‘这个模块 ,需要安装[django-smtp-ssl]。3.在使用过程中可能ssl连接回报错“SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed”,在网上搜索说时因为python2.7在连进行ssl认证促互搓,在命令行输入如下就可解决

cat /etc/ssl/certs/ca-bundle.crt >>$(python -c 'import requests; print requests.certs.where()')

,具体参考网址点击

数据库的设置

如果使用程序默认的则是sqlite数据库,在该项目中本人修改位postgresql数据库,首先Ubuntud额Pg和centos的Pg安装很不一样
ubuntu下面:

sudo apt-get install postgresql postgresql-contrib

centos 7.0安装比较麻烦,具体参考教程
安装完毕后,系统回自动生成一个数据库超级用户”postgres”,初始密码位空。后续设置如下:

sudo passwd postgres                        //输入新密码
sudo -i -u postgres                        //按提示输入新密码
psql                                       //进入postgres命令行工具psql
\password postgres                         //设置数据库密码
Enter new password
CREATE DATABASE  dbname                   //创建数据库dbname
\q                                        //退出

配置完成后记得进入manage.py目录下

python manage.py makemigrations            //生成移植中间文件
python manage.py migrate                   //同步到数据库

汉语显示

参照settings.py设置成中文即可

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

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True

4.七牛云设置

使用七牛云存储静态文件或者media文件。具体实施方案参考网址

    原文作者:AngryCJ
    原文地址: https://www.jianshu.com/p/d55726480327
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞