GAEO 預設有幾種繞徑方式,官方文件如是說:
/代表呼叫{'controller':'welcome', 'action':'index'}/foo/bar代表呼叫{'controller':'foo', 'action': 'bar'}/foo代表呼叫{'controller':'foo', 'action':'index'}
如果你也是用 gaeogen.py 產生出基本架構的話,那就還有:
/foo/bar/blah代表呼叫{'controller':'foo', 'action': 'bar', 'id': 'blah'}
官方文件中的範例跟使用 gaeogen.py 產生出的架構相同,但沒有說要怎麼取得 Controller 、 Action 和 ID ,在下對於 Python 不熟,所以又是試了一段時間才成功。
Controller 應該不用再次介紹,用 gaeogen.py 產生出來便是。Action 是指 Controller 中的 function 名稱,舉例來說, index 就是一個 Action 。
class MyController(BaseController):
def index(self): # 我就是 Action 啦!
pass
接下來的問題是要怎麼取得 ID ,我 trace 原始碼 trace 了很久(因為我是新手嘛!),才知道原來用 self.params.get('id') 便能取得。此外也可以用 self.params['id'] ,但這個方法在沒有 ID 時會發生錯誤。以下給一份完整的範例,此範例的用途是將Yahoo!奇摩字典的 Auto-completion 轉換為 Firefox 可用的 OpenSearch Suggestions 格式。
import cgi
from gaeo.controller import BaseController
from google.appengine.api import urlfetch
class YdictController(BaseController):
def index(self):
pass
def lookup(self):
p = cgi.escape(self.params['id']) if 'id' in self.params else ''
try:
result = urlfetch.fetch('http://ws.dict.tpe.yahoo.com/suggest_data.php?of=js&p=' + p, method="GET")
if result.status_code == 200 and result.content.startswith('fxsearch([') and result.content.endswith('])'):
suggestions = result.content[9:-1]
self.render(text=suggestions)
except:
pass
成果:http://bcse.appspot.com/ydict/lookup/sugges
等我試出來後,突然想到了什麼,便去查 RoR 的文件…… 果不其然,這取用方法跟 RoR 好像啊~ 看來在 GAEO 缺乏文件的現在,或許也能先參考 RoR 的文件…… XD