關於我自己

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

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 的大致過程,

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




[教學] htaccess + bower + github

由於換到了新的主機,很多東西都需要重新設定,

在這邊把過程記錄起來,順便列出好用的工具。


1.

.htaccess


要啟用這個功能,必須要先修改伺服器設定檔
sudo vim /etc/apache2/apache2.conf

將 AllowOverride 改成 All,有些伺服器還需要修改 AccessFileName 的設定
<Directory /var/www/>
        Options Indexes FollowSymLinks (把 Indexes 去掉的話,就會不會顯示目錄)
        AllowOverride All
        Require all granted
</Directory>
備註: 為了減少效能的影響,儘量對個別資料夾設定會比較好


在 .htaccess 加入最基本的內容
Options -Indexes

保護此目錄下的所有檔案
Deny from all

限制存取,並可以防止盜連網址
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://andy.revo.so/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.revo.so/fakebook/.*$ [NC]
RewriteRule \.(gif|png|jpg|py)$ http://redirect-url [R,NC]


2.

bower


需要先安裝 Node.js,一個事件驅動I/O伺服端JavaScript環境
sudo apt-get install python-software-properties
sudo apt-add-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

以上指令會安裝好 Node.js 以及 npm,用 npm 安裝 bower
sudo npm install -g bower

下載插件
sudo bower install [plugin_name]

列出目前所有插件的位置
sudo bower list --path


3.

git




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

前往 github https://github.com/,新增一個 repository


在專案資料夾中建立 repository
git init
git add some_file
git commit -m "first commit"

加入 remote repository
git remote add origin https://github.com/andyhsu5213/cam2u.git
git remote (列出全部的 remote repo)

將檔案上傳到 github
git push -u origin master
(git push [remote-name] [branch-name])
(設定 -u 後,之後可以直接 pull 不指定 remote branch)

建立 .gitignore,將不需要版本控制的檔案列在這個文件裡面

簡易範例
# comment
manage.py
*.png
*.jpg
*.gif

基礎指令
git init
git [add file_name] [--all]
git commit -m "commit message"
git rm [file_name]
git rm [file_name] --cache (取消檔案追蹤)

git status
git log

git branch // 列出所有的 branch
git branch branch_name // 新增 branch
git branch -d branch_name // 刪除 branch
git checkout [branch_name] [HEAD]
git checkout [file_name] // 將檔案還原成未修改的狀態

git push
git pull
(取得最新的 commit,但不會切換以及 merge)
(加上 --rebase 參數,會先回復成上次 pull 的 commit,套用更變之後,再加上本地的更變)

git fetch // pull and merge
git clone // init a new repo

git merge source dest
git rebase source dest // 將 source 的 commit 移到 dest 的下方

git reset HEAD^ 
(還原到上一次 commit,不會留下 commit 過的記錄,但會留下檔案,加上 --hard 參數則連檔案也一併還原)

git revert HEAD (還原倒上一次 commit,但會留下 commit 記錄)

git stash // 丟進暫存區 
git stash list // 列出所有暫存區的資料 
git stash pop