當 Python 再遇上 Mako Template


之所以說再遇上,是因為之前已經在 GAE 上玩過.不過到頭來還是沒有用上這一東西,因為本身需要安裝
不過還好的是,我算是改動了這一需求,獨立出來了..就是現在的免安裝方式應用 = =?
(如有不對,還請高手,手下留情,因為小弟還是初玩 Python..)

好吧..記錄一下心得就是
在上面主要遇到的問題是 mako 模板雖支援 Unicode ..
不過對於 UTF-8 的還是會有 Exception 出現,所以必須指定 過濾器 來處理 “default_filters=[‘decode.utf8’]”

1
2
3
4
5
6
7
8
9
10
11
12
1. 首先就是下載 mako template..
2. 以我的目錄方法就是

-- lib
|-- mako/*
-- template
|-- mako.html
-- mako.py

3. 再者就是將 lib/mako/* 的檔案進行取代
4. 將 import mako 取代為 import lib.mako
5. 將 from mako 取代為 from lib.mako

以上完成後,就寫一個測試的代碼,大約這樣:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/python
# -*- coding: utf-8 -*-

# 引入基本類庫
import cgi
import cgitb; cgitb.enable()

# 引入模版類庫
from lib.mako.template import Template
from lib.mako.lookup import TemplateLookup

# 輸出檔頭定義
print "Content-type: text/html"
print

# 接收傳送資料(這個只支援 POST 方法?)
form = cgi.FieldStorage()
sk = form.getvalue("sk")

# 條件判斷
if sk == None:
message = "Nothing"
else:
message = form.getvalue("message")

# 測試 Dict ,所謂的 Hash ?
d = {'a': 1, 'b': 2, 'c': 3}

# 渲染並輸出頁面
myLookup = TemplateLookup(directories=['./template'], input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'])
myTemplate = myLookup.get_template("mako.html")
print myTemplate.render(message=message, test = d)

而 mako.html 的內容就是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sample CGI Script</title>
</head>
<body>
<h3> Sample CGI Script </h3>
<p>Previous message: ${message}</p>
<p>form
<form method="post" action="mako.cgi">
<input type="hidden" name="sk" value="send" />
<p>message: <input type="text" name="message"/></p>
</form>
</p>
${test['a']}
</body>
</html>