關於我自己

我的相片
努力尋找人生方向的爆肝程式猿,期望可以多看多聽多學,朝向彩色的夢想前進。

2014年4月14日 星期一

[教學] 在 apache 上架設 django

在伺服器架設 django 的過程。


1. 創建專案
django-admin.py startproject project_name

2. 配置 Virtual Host
sudo vim /etc/apache2/sites-available/project_name.conf

文件內容
<VirtualHost *:80>
        ServerName domain_name
        ServerAdmin email

        WSGIScriptAlias / /var/www/project_name/project_name.wsgi
        <Directory /var/www/project_name >
                Order allow,deny
                Allow from all
        </Directory>

        Alias /static /var/www/project_name/static
        <Directory /var/www/project_name/static>
                Order allow,deny
                Allow from all
        </Directory>
</VirtualHost>

啟動 Virtual Host
sudo a2ensite project_name
sudo service apache2 restart

3. 建立 wsgi (Web Server Gateway Interface)
# coding= utf-8
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'project_name.settings'
path = '/var/www/project_name'
if path not in sys.path:
        sys.path.append(path)
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

完成後在網址輸入先前設定的 domain name,就可以看到 django 預設的頁面了


4. 在網站根目錄建立 .htaccess 文件,限制伺服器上檔案的存取
Options -Indexes

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://domain_name/.*$ [NC]
RewriteRule \.(py)$ - [F]

5. 建立 git repository


git 設定
git config --global user.name "Andy Hsu"
git config --global user.email "rastetle13@gmail.com"

新增 .gitignore 文件,列出不需要版本控制的檔案
# project ignore file list
.htaccess

project_name.wsgi

*.png
*.jpg
*.gif

初始化 repo
git init
git add --all
git commit -m "first commit"

在 github 新增 repo,在本地新增 remote repo,最後將檔案 push 到 github
git remote add origin https://github.com/account/project_name.git
git push -u origin master

6. 下載 bower 後,下載 django-bower
sudo pip install django-bower

設定 settings.py
INSTALLED_APPS = (..., "djangobower")

BOWER_COMPONENTS_ROOT = os.path.join(BASE_DIR, 'components')

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'djangobower.finders.BowerFinder',
)

BOWER_INSTALLED_APPS = (
    'jquery#2.1.0',
)

讓 django-bower 自動安裝插件
sudo python manage.py bower install

下載其他插件
sudo python manage.py bower install bootstrap

顯示目前 BOWER_INSTALLED_APPS 列表
sudo python manage.py bower freeze

bower 使用方法
sudo python manage.py bower freeze

7. 在 MySQL 新增一個 database

settings.py 設定資料庫與靜態檔案路徑
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_name',
        'USER': 'db_user',
        'PASSWORD': 'db_pwd',
        'HOST': '127.0.0.1'
    }
}

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = ()

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, "templates"),
)

初始化 django 的資料庫,並建立管理者帳號
python manage.py syncdb

再來將靜態檔案集中到設定的 STATIC_ROOT
python manage.py collectstatic

完成後,應該就可以使用管理者帳號登入管理頁面了 domain_name/admin



8. 建立應用程式 (可在不同的專案中重複利用)
python manage.py startapp app_name

進入新出現的資料夾,建立 urls.py
from django.conf.urls import patterns, include, url

from app_name import views

urlpatterns = patterns('',
    url(r'^$', views.home, name='home'),
)

編輯 views.py
from django.shortcuts import render_to_response

def home(request):
        return render_to_response('index.html')

在相同目錄下建立 templates 資料夾,並在裡面新增 index.html
<!doctype html>
<html lang="zh">
<head>
 <meta charset="UTF-8">
</head>
<body>
 Hello Django.
</body>
</html>

編輯 project_name 資料夾底下的 urls.py
url(r'', include('app_name.urls')),

編輯 project_name 資料夾底下的 settings.py
INSTALLED_APPS = (..., app_name)

在 template 文件裡面使用 static 路徑
{% load staticfiles %}
<script type="text/javascript" src='{% static 'jquery/dist/jquery.min.js' %}'></script>

(如果要使用 apps 資料夾管理 app,需修改 wsgi 文件,讓資料夾路徑加到 sys.path 裡面)



9. 資料庫設設定


安裝 South
sudo pip install South

修改 settings.py
INSTALLED_APPS = (..., south)

編輯 app_name 底下的 models.py
# coding: utf-8
from django.db import models

class Member(models.Model):
 account = models.CharField(max_length=20)
 mail = models.CharField(max_length=40)
 password = models.CharField(max_length=20)

 def __unicode__(self):
  return self.account

更新資料庫

python manage.py syncdb

建立 migrate 記錄 (第一次時使用)
python manage.py schemamigration app_name --initial

建立第一次之後的 migrate 記錄
python manage.py schemamigration app_name --auto

更新資料庫欄位
python manage.py migrate app_name



以上就是在 apache 上架設 django 的大致過程,

查閱資料的時候,就發現架構以及工具方面並不完善,之後還要繼續研究。




沒有留言:

張貼留言