Read Sean

          Read me, read Sean.
          posts - 508, comments - 655, trackbacks - 9, articles - 4

          導航

          公告


          • 關于我
          • 人生是一場對話
          • gaoyuxiang AT gmail DOT com
          • titlelogo.png

          • 我的譯作
          • Scala for the Impatient
          • Open Source SOA
          • Programming in Scala

          • 聲明
          • 所有文章和代碼在這里以"現狀"提供,作者不提供任何形式的擔保,也沒有授予除閱讀和有條件共享之外的任何權利。除非特別說明,所有文章均為本blog作者原創,如需轉載請注明出處和原作者,如用于商業目的,需作者本人書面許可。

          • 推薦文章
          • Pylons起步

          常用鏈接

          留言簿(29)

          隨筆分類(842)

          隨筆檔案(507)

          文章檔案(4)

          Friends' blogs

          搜索

          •  

          積分與排名

          • 積分 - 780753
          • 排名 - 55

          最新評論

          閱讀排行榜

          評論排行榜

          [Pylons] Routes和controller,一個簡單的例子

          Posted on 2009-01-26 16:21 laogao 閱讀(3995) 評論(0)  編輯  收藏 所屬分類: On Python

          在開始之前,說點提外話,隨著對Pylons了解的深入,你可能時不時需要看看相關組件/軟件包是否有更新出來,方法也不復雜,通過"easy_install -U [組件名]"即可,在學習或者是開發過程中,最好是保持環境相對較新,直到出現相對大的release或者即將進入產品部署階段。

          繼續介紹Pylons組件,先看個例子。首先用"paster controller hello"增加一個controller,路徑中會增加出以下兩個文件:
          controllers/hello.py
          tests/functional/test_hello.py

          分別對應新增的controller類HelloController和功能測試類TestHelloController,它們分別繼承自WSGIController->BaseController和TestCase->TestController。

          我們主要看hello.py,默認內容如下:
          ?1?import?logging
          ?2?
          ?3?from?pylons?import?request,?response,?session,?tmpl_context?as?c
          ?4?from?pylons.controllers.util?import?abort,?redirect_to
          ?5?
          ?6?from?newapp.lib.base?import?BaseController,?render
          ?7?#from?newapp?import?model
          ?8?
          ?9?log?=?logging.getLogger(__name__)
          10?
          11?class?HelloController(BaseController):
          12?
          13?????def?index(self):
          14?????????#?Return?a?rendered?template
          15?????????#???return?render('/template.mako')
          16?????????#?or,?Return?a?response
          17?????????return?'Hello?World'

          如果你的服務器沒有Ctrl-C停掉,那么這個時候你已經可以通過
          http://127.0.0.1:5000/hello/index
          看到該controller的處理結果了(Hello World)。

          簡單改造一下17行:
          ????????from?pylons?import?config
          ????????
          return?'<br/>'.join(config.keys())

          我們就可以在返回頁面上顯示出所有可以通過pylons.config訪問到的參數列表。出了返回文本,也可以通過render()方法交給頁面模板引擎生成頁面,也可以通過redirect_to()跳轉到其他URL。

          Pylons是如何找到該請求應該由HelloController的index方法來處理的呢?這背后發生了什么?答案就是Routes。

          Routes的作者是Ben Bangert,是Pylons框架三個主要作者/維護者之一,早期的版本主要是仿照Ruby on Rails的routes.rb開發的,有RoR經驗的朋友可能一眼就能發現它們之間的相似之處。目前Routes的最新版是1.10.2。

          Pylons應用中,routing的配置在config/routing.py,默認生成的內容如下:
          ?1?"""Routes?configuration
          ?2?
          ?3?The?more?specific?and?detailed?routes?should?be?defined?first?so?they
          ?4?may?take?precedent?over?the?more?generic?routes.?For?more?information
          ?5?refer?to?the?routes?manual?at?http://routes.groovie.org/docs/
          ?6?"""
          ?7?from?pylons?import?config
          ?8?from?routes?import?Mapper
          ?9?
          10?def?make_map():
          11?????"""Create,?configure?and?return?the?routes?Mapper"""
          12?????map?=?Mapper(directory=config['pylons.paths']['controllers'],
          13??????????????????always_scan=config['debug'])
          14?????map.minimization?=?False
          15?????
          16?????#?The?ErrorController?route?(handles?404/500?error?pages);?it?should
          17?????#?likely?stay?at?the?top,?ensuring?it?can?always?be?resolved
          18?????map.connect('/error/{action}',?controller='error')
          19?????map.connect('/error/{action}/{id}',?controller='error')
          20?
          21?????#?CUSTOM?ROUTES?HERE
          22?
          23?????map.connect('/{controller}/{action}')
          24?????map.connect('/{controller}/{action}/{id}')
          25?
          26?????return?map

          在這個配置中,對我們剛才的實例起到決定性作用的是第23行,我們的輸入URL為"http://127.0.0.1:5000/hello/index",其中"/hello/index"通過"/{controller}/{action}"這個表達式match出controller為hello而action為index的解析結果,從而在controllers目錄找到hello.py,和其中HelloController的index方法,進行調用。

          map.connect()在上面代碼中體現出兩種用法:
          map.connect('pattern', key=value) - 指定默認的controller、action、id等
          map.connect('pattern') - 直接指定pattern

          pattern字符串允許通配符,通常在最后一個元素上,比如'/{controller}/{action}/{*url}',將后面的整個URL片段交給前面指定的controller/action處理。除此以外,map.connect()還支持

          1- "路徑別名",如:
          map.connect('name', 'pattern', [_static=True])
          如果_static設為"True",表示為"靜態命名路徑"。
          2- 額外的匹配條件,如:
          map.connect('/{controller}/{action}/{id}', requirements={'year': '\d+',})
          map.connect('/{controller}/{action}/{id}', conditions=dict(method=['GET','POST']))

          所有的route優先級為從上到下。Routes除了提供解析進來的URL的邏輯,在我們的controller和template代碼中,我們還可以方便的通過WebHelpers的url_for()方法計算相應的URL。

          Routes 1.x中的有一些仿routes.rb功能將會在2.0中被去掉,包括Route Minimization、Route Memory、Implicit Defaults等。如果有興趣的話,可以參考一下官方文檔,這里就不一一介紹了。為什么要去掉?當然主要的動機還是減少歧義,避免一些不必要的混淆。至于深層次的原因么,可以參考Tim Peters《The Zen of Python》中的一句經典的Python哲學:Explicit is better than implicit。什么?沒有聽說過?打開python命令行,輸入"import this"后回車,慢慢體會其中的道理吧。:)


          主站蜘蛛池模板: 抚远县| 西藏| 手机| 神池县| 原阳县| 灌云县| 德清县| 张掖市| 沂源县| 泾阳县| 竹北市| 浦江县| 宁化县| 郸城县| 东源县| 灵宝市| 广丰县| 太仓市| 康平县| 宣化县| 土默特左旗| 东至县| 龙海市| 普洱| 拉孜县| 鹤峰县| 永嘉县| 错那县| 仙居县| 杂多县| 湖口县| 尼木县| 穆棱市| 邵阳市| 延长县| 大化| 宝丰县| 格尔木市| 义乌市| 栖霞市| 双峰县|