作者:maxm(2001/08/12 最後修改) 翻譯:limodou(2001/10/25)
原文:https://www.zope.org/Members/maxm/HowTo/minimal_01/
Zope 產品總給人「很難寫」的印象,但這其實是示範用的範例害的——那些範例塞滿了不必要的特性,還跳過了好幾個關鍵步驟,讓學習曲線看起來又長又陡。我第一次看到那些範例時,心裡想的是「這是巫術吧」。所以作者決定寫一系列 How-to,用最慢、最白的方式說明 Zope 編程,每一行都解釋清楚。
先寫一個能想到的最簡單 Python 類別:
class minimal:
def index_html(self):
return '<html><body>Hello World</body></html>'這在 Python 裡跑得動,在 Zope 裡卻不行。第一件事:Zope 不會公開沒有 docstring 的東西,所以加上文件字串:
class minimal:
"minimal object"
def index_html(self):
return '<html><body>Hello World</body></html>'Zope 會「公開」物件,也就是把方法變成網站上的一個頁面,因此你可以用 https://localhost:8080/minimal_id/index_html 得到 Hello World。但這個 minimal_id 從哪來?哪都沒來。任何物件都需要一個 id,Zope 才有辦法定址它。於是加上 id 屬性:
class minimal:
"minimal object"
def __init__(self, id):
"initialise a new instance of Minimal"
self.id = id # 這個傢伙不是可選的
def index_html(self):
"used to view content of the object"
return '<html><body>Hello World</body></html>'1. 所有 Zope 產品都必須被組織成 Python 套件,放在 lib/python/products/ 底下。Zope 會把這個目錄中的每個套件當成產品,啟動時設法安裝它們;套件需要在某個階段呼叫 Zope API 才能被發布。
2. 如果套件寫得正確,它就會出現在 Zope 管理介面的產品清單中。
3. 接著就能安裝它——把這個產品的一份複本放到任何你喜歡的資料夾。進入目標資料夾,從下拉選單中選這個產品即可。這正是 Zope 真正的力量:寫好一個產品,它就能在任何站點被輕易重用,你甚至可以放到 Zope.org 讓別人拿去用。
要在選單裡出現一個名字,需要 meta_type,也就是產品的唯一識別名稱。不要取成 dtml-document 或 Folder 這種會撞名的東西。
class minimal:
"minimal object"
meta_type = 'minimal' # 對這個類別的所有實例都相同
def __init__(self, id):
"initialise a new instance of Minimal"
self.id = id
def index_html(self):
"used to view content of the object"
return '<html><body>Hello World</body></html>'Zope 書中對 Item 這個基底類別的描述是:「這個基底類別提供了與 Zope 管理介面協同工作所需的基礎。繼承 Item 之後,你的產品可以獲得剪貼、粘貼、管理視圖、WebDAV 支援、基本 FTP 支援、復原、所有權與遍歷控制等一大堆特性,還有 getId()、title_or_id()、title_and_id() 與 this() 等標準方法,以及對 dtml-tree 的基本支援。Item 幾乎提供了廚房水槽以外的所有東西。」
不過還有更好的選擇:SimpleItem.SimpleItem 除了上述功能,還提供獲取(acquisition)與持續性(persistence)。它位於 OFS 套件中,必須先匯入:
from OFS import SimpleItem
class minimal(SimpleItem.SimpleItem):
"minimal object"
meta_type = 'minimal'
def __init__(self, id):
"initialise a new instance of Minimal"
self.id = id
def index_html(self):
"used to view content of the object"
return '<html><body>Hello World</body></html>'順帶一提:Python 可以一次從多個基底類別繼承,這種混搭風格叫 mixins,威力強大但不容易理解,小心使用。
標準的 Zope 方法 _setObject() 可以把物件塞進資料夾,但它是 ObjectManager 的方法,不是 minimal 的方法:
myFolder._setObject('minimal', minimal('minimal_id'))因此我們需要一個新的方法來包裝它,命名為 manage_addMinimal():
from OFS import SimpleItem
class minimal(SimpleItem.SimpleItem):
"minimal object"
meta_type = 'minimal'
def __init__(self, id):
"initialise a new instance of Minimal"
self.id = id
def index_html(self):
"used to view content of the object"
return '<html><body>Hello World</body></html>'
def manage_addMinimal(self):
"Add a Minimal to a folder."
self._setObject('minimal_id', minimal('minimal_id'))從作用域可以看出,manage_addMinimal() 是被「要把 minimal 加進去的那個資料夾」呼叫的,所以它其實屬於 ObjectManager。第一個參數是 id,這裡固定叫 minimal_id,因此同一個資料夾只能有一個實例——但這是最小版本,記得嗎?
還有個問題:這個方法沒有回傳值,瀏覽器按下確定後看起來什麼都沒發生。最簡單的解法是重導到 index_html。RESPONSE 物件每次呼叫方法時都會作為參數傳入,而 redirect() 就在其中:
def manage_addMinimal(self):
"Add a Minimal to a folder."
self._setObject('minimal_id', minimal('minimal_id'))
RESPONSE.redirect('index_html')目錄結構:
minimal/ minimal.py __init__.py
__init__.py 用來告訴 Zope 這是一個產品,以及要新增實例時該呼叫哪個方法:
import minimal
def initialize(context):
"""Initialize the minimal product."""
context.registerClass(
minimal.minimal,
constructors = (
minimal.manage_addMinimal, # 有人新增產品時呼叫
)
)initialize() 是 Zope 啟動時呼叫的,這也是為什麼安裝新產品必須重啟 Zope。registerClass() 的第一個參數是要註冊的類別,第二個參數是作為建構子(constructor)的方法元組。注意方法名後面不要加括號——我們不是要執行它,只是告訴 Zope 是哪個方法。
這就是一個功能完整的 Zope 最小產品了。它還很粗糙,沒有持續性、沒有安全與使用者管理,但寫一個類別需要知道的都在這裡。
最明顯的改善是新增實例時能自行指定 id。做法是加一個表單:
def manage_addMinimal(self, id, RESPONSE=None):
"Add a Minimal to a folder."
self._setObject(id, minimal(id))
RESPONSE.redirect('index_html')
def manage_addMinimalForm(self):
"The form used to get the instance' id from the user."
return """<html><body>
Please type the id of the minimal instance:
<form name="form" action="manage_addMinimal">
<input type="text" name="id">
<input type="submit" value="add">
</form></body></html>"""同時 __init__.py 要改成註冊 manage_addMinimalForm 作為第一個建構子,manage_addMinimal 作為第二個。
最後還有一個小瑕疵:點進 minimal_id/manage_workspace 會跳錯誤,因為我們沒定義管理畫面。加上 manage_options 即可:
manage_options = (
{'label': 'View', 'action': 'index_html'},
)這樣管理介面會出現一個名為 View 的頁籤,預設進入 index_html。
加幾個方法看看效果,跟 mod_perl、.asp 或 .php 沒有太大差別:
def counter(self):
"Shows the numbers from 0 to 10"
result = '<html><body>\n'
for i in range(10):
result = result + str(i) + '\n'
return result + '</body></html>\n'
def squareForm(self):
"User input form for the square method"
return """<html><body>
Please type the number you want squared:
<form name="form" action="square">
<input type="text" name="value:int">
<input type="submit" value="Square">
</form></body></html>"""
def square(self, value=0):
"Returns the input value squared"
return """<html><body><b>The result is:</b> %s</body></html>""" % str(value*value)這裡示範的不是 Zope 平常的用法,但它是產品建立最好的入門起點,後續的機制都可以從這個例子延伸。Zope 內建了討論區、會話、使用者管理這些東西,所以相對於 mod_perl、.asp、.php 看起來複雜——複雜是因為它替你想得更多。當你替客戶做完一個應用,客戶要求重用、要求權限管理、要求刪除機制,然後又買了一家德國公司要整併討論區時,你就會明白這種「陡峭的學習曲線」其實是往後越走越輕鬆。
註:原文對 Mixin 的解釋略有爭議,比較準確的說法是於執行期重新定義類別的基底,讓新產生的實例具備新的屬性與方法。