在dotcloud上部署Django全程記錄
近日重新研究python和Django, 想動手做了個網(wǎng)站試驗,無奈的是GAE被墻,SAE的python內(nèi)測還排在100位開外,只好用Dotcloud先練練手了,網(wǎng)上看到一些dotcloud部署的文章,命令都是舊版的,比較坑爹。因為之前在上面部署過php+mysql, 難度不大,但這次部署Django卻并不容易,但好歹也算弄出來了,呵呵,先看成果,這是部署后的網(wǎng)址
http://www.onepythoner.tk
1. 在dotcloud 首頁(https://www.dotcloud.com/):get started in seconds!后面的文本框輸入你的Email 地址如 516974090#qq.com ,點擊Try it now后,郵箱會收到一封激活郵件,同時數(shù)秒后頁面跳轉(zhuǎn)到Dotcloud文檔,點擊郵件的鏈接地址激活帳號。
——————————————-
2.填寫用戶名密碼,點Sign Up完成激活 ( 用戶名只能用數(shù)字和字母,如:falconchen)點擊頁面頂部的Dashboard進入控制面板。
如果之前部署過應(yīng)用會在右側(cè)Applications處看到應(yīng)用的鏈接。
如果沒有只會顯示先安裝CLI.
——————————————-
3.同樣,點擊Dashboard旁邊的Settings鏈接進入設(shè)置面板。記錄下API Key,這個后面會用到。
——————————————-
4.好了,現(xiàn)在開始安裝CLI,
dotcloud 文檔鏈接在這里:http://docs.dotcloud.com/firststeps/install/
其實已經(jīng)很詳細了。不想看英文的跟我操作。
Linux下安裝是很簡單的,不說了。
在Windows是非官方支持的安裝方法,需要先安裝Cygwin。
4.1 下載cygwin鏈接:http://cygwin.com/setup.exe,一直點擊下一步,國內(nèi)有163做的鏡像,下載組件速度非常快,很方便。
4.2以下的包為必選安裝,用searsh慢慢挑,找到后單擊后面的空格框選中,安裝Bin
注意的 python要選2.6以上的版本
net/openssh
net/rsync
devel/git
devel/mercurial
python/python (make sure it’s at least 2.6!)
web/wget
4.3 完成后點下一步即可,Cygwin會補全依賴組件,然后自動聯(lián)網(wǎng)下載。這個跟linux下的APT,YUM包管理器挺像的。然后等待安裝過程結(jié)束
4.4安裝easy_install。easy_install是由PEAK(Python Enterprise Application Kit)開發(fā)的setuptools包里帶的一個命令,使用easy_install實際上是在調(diào)用setuptools來完成安裝模塊的工作。更多關(guān)于setuptools和easy_install的介紹請參考這篇文章:
http://www.juziblog.com/?p=365001
打開cygwin終端,輸入以下命令
wget http://peak.telecommunity.com/dist/ez_setup.py
回車后繼續(xù)輸入
python ez_setup.py
然后安裝pip。pip與easy_install是類似,都是python下的模塊安裝命令,區(qū)別和用法請參考這篇文章:http://blog.sina.com.cn/s/blog_6768f2290100tzau.html
easy_install pip
最后用pip安裝dotcloud模塊
pip install dotcloud
安裝完成后鍵入
dotcloud
會提示您輸入api key(即第3步記錄的密鑰)
粘貼進去,注意不要混入回車或空格
4.5 回車后輸入 dotcloud -h,如果顯示如圖說明安裝成功。
——————————————-
以前用PHP+Mysql在Dotcloud上部署過一個Wordpress的博客:http://www.onephper.tk
這次我們來部署Python+MySQL+Django,同樣使用tk免費域名。
——————————————-
5.不使用以下的安裝方法,請忽略,推薦安裝方式請看第6步:
5.1為了兼容以后SAE的python應(yīng)用(雖然內(nèi)測資格還沒到手),我們使用與SAE上相同的版本
Django-1.2.7,下載地址: http://www.djangoproject.com/download/1.2.7/tarball/
終端輸入:
wget http://media.djangoproject.com/releases/1.2/Django-1.2.7.tar.gz
tar xzvf Django-1.2.7.tar.gz
cd Django-1.2.7
pwd
復(fù)制屏幕輸出的內(nèi)容,同樣,后面會用到
/home/Administrator/Django-1.2.7
為兼容Windows下做開發(fā),使用pth文件方式安裝 ,參考《The django Book》
http://djangobook.py3k.cn/2.0/chapter02/
終端下用以下命令找到python的site packages目錄
python -c ‘import sys,pprint;pprint.pprint(sys.path)’
于是確定site-packages目錄如下
/usr/lib/python2.6/site-packages
cd /usr/lib/python2.6/site-packages
echo /home/Administrator/Django-1.2.7 >django.pth
less django.pth
發(fā)現(xiàn)上面路徑已經(jīng)寫入文件即可。
5.2 把django的bin目錄加入系統(tǒng)path
echo export PATH=”/home/Administrator/Django-1.2.7/django/bin:$PATH” >>~/.bashrc
source ~/.bashrc
好了,現(xiàn)在我們看看是否安裝成功。進入交互解釋器
$ python
Python 2.6.7 (r267:88850, Feb 2 2012, 23:50:20)
[GCC 4.5.3] on cygwin
Type “help”, “copyright”, “credits” or “license” for more information.
執(zhí)行python語句
>>> import django
>>> django.VERSION
(1, 2, 7, ‘final’, 0)
一切看起來很順利!這樣Django就裝好了。
——————————————-
6。接下來讓我們繼續(xù)部署dotcloud應(yīng)用
exit()退出python解釋器,回到命令行下
$ cd ~
$ mkdir mydjango
6.1在mydjango目錄下創(chuàng)建 dotcloud.yml,這是DotCloud的Build File
用vi或者在Windows資源管理器(我的cygwin裝在F盤,mydjango目錄位于F:\cygwin\home\Administrator\mydjango)下直接創(chuàng)建dotcloud.yml文件并向其寫入
www:
type: python
6.2同樣在此目錄新建requirements.txt文件,并寫入Django==1.2.7
當(dāng)然也可以使用最新版本的Django,這里安裝1.2.7版本,目的是為了方便將來與SAE對接,SAE里的Django就是使用這個版本的。(仍然在求內(nèi)測資格)
用pip安裝器執(zhí)行在線安裝(這貨很強,可以但不限于pypi里的包,還可以從Git,Mercurial,Bazaar,SVN源里安裝)
關(guān)于Pypi,請參考:http://pypi.python.org/pypi
關(guān)于pip安裝器和requirements.txt請參考:http://www.pip-installer.org/en/latest/index.html
6.3安裝Djang
命令行下執(zhí)行
pip install -r ~/mydjango/requirements.txt
把Django的bin目錄加入系統(tǒng)path
$ echo export PATH=”/lib/python2.6/site-packages/django/bin:$PATH” >>~/.bashrc
$ source ~/.bashrc
$ echo $PATH
如果提示-bash: export: `****’: not a valid identifier,因為cygwin會把WIN下的系統(tǒng)路徑加入PATH,當(dāng)路徑存在空格時就會發(fā)生這些情況。我的辦法就是把它們用”"引起來,在.bashrc里手動改成如”/cygdrive/c/Program Files/TortoiseSVN/bin”的形式。或者實在用不到的就刪了吧
6.4創(chuàng)建一個django應(yīng)用,我就命名為hello吧。
$ cd mydjango/
$ django-admin.py startproject hello
$ ls hello
就看到了django自動創(chuàng)建的文件
__init__.py manage.py settings.py urls.py
6.4在mydjango目錄下創(chuàng)建wsgi.py文件,用于橋接python和Django 應(yīng)用
寫入以下內(nèi)容:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = ‘hello.settings’
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
6.4 PUSH 代碼
$ dotcloud push hello
多次出錯后終于,終于成功了,內(nèi)牛滿面。這網(wǎng)絡(luò),真是蛋都碎了~
$ dotcloud push hello
# upload /home/Administrator/mydjango ssh://dotcloud@uploader.dotcloud.com:443/hello
# rsync
Pseudo-terminal will not be allocated because stdin is not a terminal.
building file list … done
sent 223 bytes received 12 bytes 7.46 bytes/sec
total size is 4.63K speedup is 19.69
14:55:34 —> Deploy of “hello” scheduled for revision rsync-1333983305890 at 2012-04-09 14:55:34
14:55:34 —> Building the application…
14:55:35 [www] Build started for revision rsync-1333983305890 (incremental build from revision rsync-1333983054459)
14:55:46 [www] Requirement already satisfied (use -upgrade to upgrade): Django==1.2.7 in /home/dotcloud/env/lib/python2.6/site-packages (from -r requirements.txt (line 1))
14:55:46 [www] Cleaning up…
14:55:52 [www] Build completed successfully. Compiled image size is 13MB
14:55:52 —> Initializing new services… (This may take a few minutes)
14:55:52 —> No new services found
14:55:52 —> All services have been initialized. Deploying code…
14:55:52 [www.0] Deploying build revision rsync-1333983305890…
14:55:57 [www.0] Running postinstall script…
14:55:59 [www.0] Launching…
14:55:59 [www.0] Waiting for the service to become responsive…
14:56:00 [www.0] Re-routing traffic to the new build…
14:56:01 [www.0] Successfully deployed build revision rsync-1333983305890
14:56:01 —> Deploy finished
Deployment finished. Your application is available at the following URLs
www: http://hello-falconchen.dotcloud.com/
訪問成功后給出的url:http://hello-falconchen.dotcloud.com/
這個地址也可以通過下面的命令取得
$ dotcloud info hello
如果看到It works就說明部署成功了。像我的這樣
——————————————-
7.別名 (參考文章: http://blog.yangtse.me/2011/10/wordpress-dotcloud/)
7.1 不能使用一級域名,如onepythoner.tk, 但支持 www.onepythoner.tk這樣的二級域名。
終端執(zhí)行命令
$ dotcloud alias add hello.www www.onepythoner.tk
輸出以下信息表示成功
Ok. Now please add the following DNS record:
www.onepythoner.tk. IN CNAME gateway.dotcloud.com.
dot.tk控制面板中配置CNAME如下
——————————————-
8 部署數(shù)據(jù)庫
8.1 這里我使用mysql ,修改dotcloud.yml,內(nèi)容如下
www:
type: python
db:
type: mysql
保存后執(zhí)行一次push
8.2向settings.py加入數(shù)據(jù)庫驗證信息,
dotcloud中關(guān)于應(yīng)用的一些環(huán)境設(shè)置放在服務(wù)器/home/dotcloud/environment.json里,包括和數(shù)據(jù)庫連接有關(guān)的信息。
可以執(zhí)行此信息查看
$ dotcloud ssh hello.www
# $SHELL
dotcloud@hello-default-www-0:~$ vi /home/dotcloud/environment.json
8.3創(chuàng)建數(shù)據(jù)庫,命名為hello
使用SSH登陸
#注意:這不是最佳實踐,為方便自動化部署,相關(guān)語句寫在放在postinstall腳本可能更佳。
$ dotcloud ssh hello.db
mysql@hello-default-db-0:~$ mysql -v
mysql> CREATE DATABASE IF NOT EXISTS `hello`;
————-
CREATE DATABASE IF NOT EXISTS `hello`
————-
Query OK, 1 row affected (0.01 sec)
8.4 回到本地繼續(xù)編輯settings.py,修改如下
# Django settings for hello project.
import json
with open(‘/home/dotcloud/environment.json’) as f:
env = json.load(f)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# (‘Your Name’, ‘your_email@domain.com’),
)
MANAGERS = ADMINS
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’, # Add ‘postgresql_psycopg2′, ‘postgresql’, ‘mysql’, ‘sqlite3′ or ‘oracle’.
‘NAME’: ‘hello’, # Or path to database file if using sqlite3.
‘USER’: env['DOTCLOUD_DB_MYSQL_LOGIN'], # Not used with sqlite3.
‘PASSWORD’: env['DOTCLOUD_DB_MYSQL_PASSWORD'], # Not used with sqlite3.
‘HOST’: env['DOTCLOUD_DB_MYSQL_HOST'], # Set to empty string for localhost. Not used with sqlite3.
‘PORT’: env['DOTCLOUD_DB_MYSQL_PORT'], # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
#…
為了使用管理界面,我們開啟admin app
INSTALLED_APPS = (
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.sites’,
‘django.contrib.messages’,
# Uncomment the next line to enable the admin:
‘django.contrib.admin’, #去除前面的#號
# Uncomment the next line to enable admin documentation:
# ‘django.contrib.admindocs’,
)
8.5 打開hello/urls.py文件,去除以下行的注釋
#from django.contrib import admin
#admin.autodiscover()
#(r’^admin/’, include(admin.site.urls))
8.6用postinstall自動調(diào)用syscdb
在mydjango下新建文件postinstall(注意編碼為ANSI,否則有可能部署失敗),并寫入以下內(nèi)容:
#!/bin/sh
python hello/manage.py syncdb -noinput
python mkadmin.py #下面用到
再新建 mkadmin.py,寫入以下內(nèi)容,
#!/usr/bin/env python
from wsgi import *
from django.contrib.auth.models import User
u, created = User.objects.get_or_create(username=’admin’)
if created:
u.set_password(‘password’)
u.is_superuser = True
u.is_staff = True
u.save()
以上腳本創(chuàng)建了一個用戶名為admin,密碼為password的超級用戶
執(zhí)行一次push后可以鍵入
http://www.onepythoner.tk/admin/即可看到不帶樣式的登錄管理界面
——————————————-
9.處理靜態(tài)文件和媒體資源
首先在settings.py中指定
STATIC_ROOT, STATIC_URL, MEDIA_ROOT, and MEDIA_URL.
我們把靜態(tài)文件放置在/home/dotcloud/data目錄下,因為data目錄的數(shù)據(jù)在每次push中保持永久不變。如果文件放置在code或current目錄下可能會在代碼push后被擦除。
修改settings.py相關(guān)常量,貌似1.2.x的django并不區(qū)分MEDIA與STATIC
MEDIA_ROOT = ‘/home/dotcloud/data/media/’
MEDIA_URL = ‘/media/’
STATIC_ROOT = ‘/home/dotcloud/data/static/’
STATIC_URL = ‘/static/’
ADMIN_MEDIA_PREFIX = ‘/static/admin/’
在mydjango下新建 nginx.conf
寫入以下內(nèi)容
location /media/ { root /home/dotcloud/data ; }
location /static/ { root /home/dotcloud/data ; }
編輯postinstall,追加以下內(nèi)容
mkdir -p /home/dotcloud/data/media /home/dotcloud/data/static
python hello/manage.py collectstatic -noinput
執(zhí)行一次push
——————————————-
CSS和javascript還是沒有辦法加載,原因是1.2.x的靜態(tài)文件處理跟1.3+的有所不同,在Django1.3+里,MEDIA跟STATIC是分離的, MEDIA是存放用戶上傳的文件,Static是用來存放收集文件,而推薦用來放站點css,javascript的是app下的static目錄。
而且這里有個問題,如果要使用SAE或者GAE這類代碼文件跟靜態(tài)文件放在不同的服務(wù)器,不同URL的主機,處理起來也可能不一樣,1.3+好歹也算有個collectstatic命令可以提取靜態(tài)文件,1.2.x要怎么處理?
——————————————-
暫時使用這樣的解決方法,用pip安裝django-staticfiles,django1.3+只不過是把這個app集成進去了,而用pip也可以實現(xiàn)獨立安裝,甚至版本可能會比最新Django發(fā)行的要高。
參考:http://pypi.python.org/pypi/django-staticfiles/
安裝方法很簡單,即把django-staticfiles寫入requirements.txt里,再執(zhí)行一次
pip install -r ~/mydjango/requirements.txt
修改settings.py
INSTALL_APPS =[
#...
"staticfiles",
]
向postinstall加入 ,后面的參數(shù)一定是-noinput
python hello/manage.py collectstatic -noinput
push代碼后
或者,如果想要交互執(zhí)行,可SSH到服務(wù)器
$ dotcloud ssh hello.www
$ cd code
$ python hello/manage.py collectstatic
這時會詢問是否執(zhí)行,輸入yes后腳本開始執(zhí)行
輸入http://www.onepythoner.tk/admin/,即可看到效果,靜態(tài)文件得到正確的解析,至此大功告成
——————————————-
完整代碼下載:mydjango
安裝nginx和uWSGI的方法, http://studio.zeuik.com/?p=791
【編輯推薦】