URL Routing in GAEO

GAEO 預設有幾種繞徑方式,官方文件如是說:

  1. / 代表呼叫 {'controller':'welcome', 'action':'index'}
  2. /foo/bar 代表呼叫 {'controller':'foo', 'action': 'bar'}
  3. /foo 代表呼叫 {'controller':'foo', 'action':'index'}

如果你也是用 gaeogen.py 產生出基本架構的話,那就還有:

  1. /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

2 Comments

  1. 歹勢呀 XD 因為還忙著寫 code 就比較沒時間寫文件了 XD

  2. 沒關係啦!我也覺得先有 code 比較重要 XD
    感謝你提供的好用 framework :)

Leave your thoughts
  • You can use some HTML in your comment.
  • Your comment may not display immediately due to spam filtering. Please wait for moderation.