經(jīng)過(guò)了一個(gè)星期的努力捏题,終于是把自己的個(gè)人博客上線到自己的阿里云服務(wù)器上www.fortable.cn,半年前買的域名和服務(wù)器也是終于有了內(nèi)容纵菌。在這期間,也經(jīng)過(guò)了不少坑玄柠,現(xiàn)在把這些都記錄下來(lái)突梦。我將從django(zinnia)-->uwsgi+nginx-->postgresql-->qiniuyun這個(gè)順序逐一記錄。由于本人在開發(fā)的時(shí)候是使用的ubuntu16.04 64位系統(tǒng)羽利。aliyun上使用的是centos7.3 64位系統(tǒng)宫患。在移植的過(guò)程中還經(jīng)過(guò)了不少坑,現(xiàn)在一一記錄下來(lái)铐伴。
目錄 (Table of Contents)
[TOC]
1.zinnia
本人采用的是github上比較熱門的django開源項(xiàng)目zinnia-0.18.1撮奏,詳細(xì)的使用方法查看此開源項(xiàng)目的官方文檔。在此開發(fā)過(guò)程中發(fā)現(xiàn)所有項(xiàng)目的官方文檔和程序的log日志是解決問(wèn)題的終極大招当宴。
安裝virtualenv
每一個(gè)python項(xiàng)目最好使用獨(dú)立的python環(huán)境.
pip install virtualenv #安裝virtualenv
cd yourProPath/ #進(jìn)入你的項(xiàng)目目錄上一級(jí)
virtualenv --no-site-packages venv #創(chuàng)建一個(gè)沒(méi)有其他多余安裝包的干凈環(huán)境畜吊,生成目錄venv。
source venv/bin/activate #激活環(huán)境
pip install "packages" #安裝你所需要的包户矢,切記前面不要加sudo,否則pytho包會(huì)安裝在電腦環(huán)境中
deactivate #退出當(dāng)前python環(huán)境
加速pip install 方法
1.proxychains pip install package; #如果電腦上安裝代理可以使用官方鏡像
2.pip install 'package' -i http://pypi.douban.com/simple --trusted-host pypi.douban.com #國(guó)內(nèi)使用豆瓣鏡像
注:如果windows用戶出現(xiàn)錯(cuò)誤: failed to compile wheel 根據(jù)提示去微軟官網(wǎng)下載 VCforpy27.msi 安裝即可
安裝項(xiàng)目所需要的python包
所需要下載的python包配置清單已經(jīng)上傳至我的github空間,下載下來(lái)然后使用
pip install -r require.txt
運(yùn)行zinnia
依照zinnia的官方教程玲献,對(duì)settings.py和urls.py進(jìn)行設(shè)置,然后
python manage.py migrate #將model數(shù)據(jù)寫入數(shù)據(jù)庫(kù)表中梯浪,創(chuàng)建數(shù)據(jù)庫(kù)表
python manage.py runserver 0.0.0.0:8080 #將djano服務(wù)拉起來(lái)捌年,即可在瀏覽器中看見(jiàn)頁(yè)面
###**設(shè)置admin用戶**
python manage.py createsuperuser #按照提示輸入用戶名密碼即可
python manage.py changepassword username #修改用戶名密碼
python manage.py shell #進(jìn)入django SHELL 界面
其他的一些功能設(shè)置可以參考官方教程。
2.Centos上利用 uwsgi+nginx部署django
在centos上安裝uwsgi和nginx
安裝uwsgi: pip install uwsgi
安裝nginx: sudo yum install nginx
設(shè)置uwsgi和nginx
新建一個(gè)uwsgi.ini設(shè)置如下:
[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 #日志文件地址挂洛,需要自己創(chuàng)建
vim /etc/nginx/nginx.conf 設(shè)置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用戶 不然會(huì)出現(xiàn)訪問(wèn)permission denied
worker_processes auto;
error_log /var/log/nginx/error.log; //error log 日志 在調(diào)試的時(shí)候非常有用
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/; #設(shè)置為django的靜態(tài)文件夾(后面講這個(gè)文件夾怎么生成)
}
location / {
uwsgi_pass 127.0.0.1:3316; #uwsgi的對(duì)接port口
include uwsgi_params; #在/etc/nginx的目錄里面的文件 uwsgi的補(bǔ)充協(xié)議
# 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
則配置好了對(duì)應(yīng)的nginx+uwsgi.在對(duì)nginx.conf再次編輯時(shí)礼预,可以使用nginx -t檢查配置文件正確與否,如果返回ok,用 -s reload 重新加載配置文件虏劲,nginx里面一定要設(shè)置django的靜態(tài)文件夾托酸,不然網(wǎng)頁(yè)會(huì)找不到樣式
3.zinnia進(jìn)階--settings.py文件詳解
下面是我的settings.py的全部?jī)?nèi)容
""
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
靜態(tài)文件的設(shè)置
如果需要修改zinnia模板的對(duì)應(yīng)靜態(tài)圖標(biāo)和圖片等,則需要重載靜態(tài)文件或者media文件柒巫。static files和media files的設(shè)置和網(wǎng)頁(yè)樣式的自定義差不多励堡,也是重載對(duì)應(yīng)的目錄,并將對(duì)應(yīng)的地址注冊(cè)到settings.py文件里面堡掏,具體參考django settings 官方文檔 .主要settings.py設(shè)計(jì)代碼如下:
#static settings
STATIC_URL = '/static/' #和manage.py同級(jí)目錄的static文件夾
STATIC_ROOT = os.path.join(BASE_DIR,"staticfile/") #python manage.py collectstatic 靜態(tài)文件存放地址
STATICFILES_DIRS = [os.path.join(BASE_DIR,"static"),] #在這里面加入你所需要更改的靜態(tài)文件
#media settings
MEDIA_URL ='/media/' #和manage.py同級(jí)目錄的media文件夾
MEDIA_ROOT = os.path.join(BASE_DIR,'media') #media文件路由地址应结,保存上傳文件的文件夾
STATIC_ROOT:運(yùn)行上邊提到的命令:python manage.py collectstatic 之后靜態(tài)文件將要復(fù)制到的目錄,這個(gè)目錄只有在運(yùn)行collectstatic時(shí)候才會(huì)用到泉唁,不能想當(dāng)然的以為這個(gè)目錄和MEDIA_ROOT的作用是相同的鹅龄,否則在開發(fā)環(huán)境的時(shí)候可能一直無(wú)法找到靜態(tài)文件。
STATIC_URL:設(shè)置的static file的起始url亭畜,這個(gè)只是在template里邊引用到扮休,這個(gè)參數(shù)和MEDIA_URL的含義相同,
STATICFILES_DIRS:和TEMPLATE_DIRS的含義差不多贱案,就是除了各個(gè)app的static目錄以外還需要管理的靜態(tài)文件設(shè)置,比如項(xiàng)目的公共文件差不多。
各個(gè)app目錄下的靜態(tài)文件static/django會(huì)自動(dòng)找到宝踪,這個(gè)點(diǎn)和app下的templates目錄下差不多侨糟。
網(wǎng)頁(yè)樣式的自定義
靜態(tài)模板的修改,可以參考馬志鋒--邊做邊學(xué)瘩燥,Python&Django實(shí)戰(zhàn)教程-10-修改顯示模板秕重。主要是重載對(duì)應(yīng)的你所所需的模板文件比如skeleton.html和base.html,并且將重載的文件夾地址寫入對(duì)應(yīng) TEMPLATES.’DIRS‘里面
mail郵箱的設(shè)置
剛開始參考網(wǎng)上的設(shè)置厉膀,找了好久沒(méi)有找到溶耘,終于找到有一個(gè)參考的答案
settings.py的設(shè)置如下:
#EMAIL
#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #不是用這個(gè)
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' #正確的用這個(gè)
# 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不同的凳兵,只有使用默認(rèn)的ssl 465端口。1.你需要把你的郵箱開啟smtp服務(wù)企软,我這里使用的是QQ郵箱庐扫,將會(huì)生成一個(gè)password,將該password放置在settings.py的文件里面仗哨。2.為了使用’django_smtp_ssl.SSLEmailBackend‘這個(gè)模塊 形庭,需要安裝[django-smtp-ssl]。3.在使用過(guò)程中可能ssl連接回報(bào)錯(cuò)“SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed”厌漂,在網(wǎng)上搜索說(shuō)時(shí)因?yàn)閜ython2.7在連進(jìn)行ssl認(rèn)證促互搓萨醒,在命令行輸入如下就可解決
cat /etc/ssl/certs/ca-bundle.crt >>$(python -c 'import requests; print requests.certs.where()')
,具體參考網(wǎng)址點(diǎn)擊
數(shù)據(jù)庫(kù)的設(shè)置
如果使用程序默認(rèn)的則是sqlite數(shù)據(jù)庫(kù)苇倡,在該項(xiàng)目中本人修改位postgresql數(shù)據(jù)庫(kù)富纸,首先Ubuntud額Pg和centos的Pg安裝很不一樣
ubuntu下面:
sudo apt-get install postgresql postgresql-contrib
centos 7.0安裝比較麻煩,具體參考教程
安裝完畢后雏节,系統(tǒng)回自動(dòng)生成一個(gè)數(shù)據(jù)庫(kù)超級(jí)用戶"postgres"胜嗓,初始密碼位空。后續(xù)設(shè)置如下:
sudo passwd postgres //輸入新密碼
sudo -i -u postgres //按提示輸入新密碼
psql //進(jìn)入postgres命令行工具psql
\password postgres //設(shè)置數(shù)據(jù)庫(kù)密碼
Enter new password
CREATE DATABASE dbname //創(chuàng)建數(shù)據(jù)庫(kù)dbname
\q //退出
配置完成后記得進(jìn)入manage.py目錄下
python manage.py makemigrations //生成移植中間文件
python manage.py migrate //同步到數(shù)據(jù)庫(kù)
漢語(yǔ)顯示
參照settings.py設(shè)置成中文即可
# 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.七牛云設(shè)置
使用七牛云存儲(chǔ)靜態(tài)文件或者media文件钩乍。具體實(shí)施方案參考網(wǎng)址