2013年7月13日10:36:53:接上篇,bae部署django沒成功,轉戰阿里雲。。
阿里雲服務器最便宜69/月,現在有個活動,新用戶送20元現金券,我就花了RMB 49買了一個,操作系統選的是ubuntu1204安全加強版。
1.putty登陸遠程主機
putty下載地址:http://the.earth.li/~sgtatham/putty/latest/x86/putty.zip,解壓后直接運行putty.exe即可。
2.Xftp與遠程主機傳文件
Xftp下載地址http://www.onlinedown.net/soft/143.htm
以上兩步看aliyun的幫助文檔即可,easy,http://help.aliyun.com/manual?spm=0.0.0.0.ZERNiU&helpId=1846
3.安裝apache+mysql+python+django
管理mysql就用phpmyadmin了,這樣就得再裝個php,命令如下
apt-get install apache2 php5 libapache2-mod-php5 mysql-server libapache2-mod-auth-mysql php5-mysql phpmyadmin
期間要求輸mysql root用戶密碼和phpmyadmin的登陸密碼
python系統自帶了。需要裝python-mysqldb
apt-get install python-mysqldb
安裝一個mod_wsgi,此物就是將Python應用部署到Apache上的。
apt-get install libapache2-mod-wsgi
鏈接phpmyadmin
ln -s /usr/share/phpmyadmin /var/www/phpmyadmin
python ubuntu已經自帶了,需要安裝一個python-mysqldb
apt-get install python-mysqldb
django從官網下載,我當前下載的版本是1.5.1,然后按照官網的說明安裝。
重啟Apache2的命令:
sudo /etc/init.d/apache2 restart
4.啟動一個django站點
切換到/srv目錄下,啟動一個django站點
django-admin.py startproject mysite
5. 下面是配置apache了
django官方有一篇如何配置的文檔,mod_wsgi官網也有如何配置的文檔。主要一點mod_wsgi有兩種工作模式,嵌入到Apache和作為線程的守護模式。官方推薦用守護模式,守護模式沒研究,嵌入模式最簡單,先用嵌入模式。
編輯Apache的配置文件
gedit /etc/apache2/sites-available/default
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
WSGIScriptAlias /app/ /srv/mysite/mysite/wsgi.py
<Directory /srv/mysite/mysite>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
</VirtualHost>
重點就是在原來文件的基礎上增加了
WSGIScriptAlias /app/ /srv/mysite/mysite/wsgi.py <Directory /srv/mysite/mysite> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory>
還有編輯/etc/apache2/httpd.conf文件,增加下面這行
WSGIPythonPath /srv/mysite
然后重啟apache服務就OK了!
此時通過瀏覽器訪問你的雲服務器主機地址xx:xx:xx:xx/app/,就可一看到django默認頁面了!
6.連接數據庫
編輯mysite/settings.py,修改DATABASES一項
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'db_name', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'your_mysql_passwd', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
django默認安裝的應用有:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
#'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
運行下面的命令,同步數據庫,為默認安裝的應用創建table:
python manage.py syncdb
7.創建一個app+模型
輸入下面的命令,創建一個叫polls的應用
python manage.py startapp polls
接下來創建模型(models),按照django官網教程的例子,編輯polls/models.py
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
class Choice(models.Model): poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice
這里的意思創建了兩個模型:Poll、Choice。__unicode__方法是定義模型默認顯示的內容。
激活模型,編輯mysite/settings.py中INSTALLED_APP,如下:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'polls',
)
同步一下數據庫
python manage.py syncdb
可以在shell下輸入一些python語句,為模型創建內容。進入shell環境的命令為:
python manage.py shell
例如:
>>> from polls.models import Poll, Choice # Import the model classes we just wrote. # No polls are in the system yet. >>> Poll.objects.all() [] # Create a new Poll. >>> from django.utils import timezone >>> p = Poll(question="What's new?", pub_date=timezone.now()) # Save the object into the database. You have to call save() explicitly. >>> p.save() # Now it has an ID. Note that this might say "1L" instead of "1", depending # on which database you're using. That's no biggie; it just means your # database backend prefers to return integers as Python long integer # objects. >>> p.id 1
8.配置url+創建視圖
編輯mysite/urls.py
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'simple.views.home', name='home'),
# url(r'^simple/', include('simple.foo.urls')),
url(r'^polls/', include('polls.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
編輯polls/urls.py (此文件不存在,新建一個)
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='home'),
url(r'^show/$', views.show_all, name='show'),
)
創建views.index視圖,編輯polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
此時訪問主機名xx:xx:xx:xx/app/polls 就可以看到hello world視圖了!
9.開啟admin應用
首先編輯settings.py,打開admin應用
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'polls',
)
同步下數據庫
python manage.py syncdb
編輯mysite/urls.py,打開admin的視圖
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'simple.views.home', name='home'),
# url(r'^simple/', include('simple.foo.urls')),
url(r'^$', 'polls.views.index'),
url(r'^polls/', include('polls.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
設置admin的靜態文件。首先編輯apache2的配置文件,讓apache提供靜態文件的服務。編輯完之后,需要重啟apache。
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
AliasMatch ^/([^/]*\.css) /srv/mysite/static/styles/$1
Alias /media/ /srv/mysite/media/
Alias /static/ /srv/mysite/static/
<Directory /srv/mysite/static>
Order deny,allow
Allow from all
</Directory>
<Directory /srv/mysite/media>
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / /srv/mysite/mysite/wsgi.py
<Directory /srv/mysite/mysite/>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
</VirtualHost>
在/srv/mysite/下新建一個static和media文件夾,將django/contrib/admin/static/admin這個文件夾復制到/srv/mysite/static/下。
在瀏覽器試一下,xx:xx:xx:xx/admin,此時有admin界面了。
注:這里有個建議,刪掉polls/urls.py,將鏈接分發統一放到mysite/urls.py這一個文件中去。原因是,過程中遇到一些莫名的問題,放在一個文件中就OK,此問題遺留。
下面把我們剛才創建的模型注冊到admin中去,(admin的作用無需解釋,走一遍django tutorial就了解了)。
在polls/下新建一個admin.py,編輯其內容如下即可:
from django.contrib import admin from polls.models import Poll admin.site.register(Poll)
至此,本文結束,阿里雲+django搭建完畢,剩下的是django的開發工作了。
