2016-11-18 17 views
1

我有一個簡單的TurboGears 2腳本,命名爲app.py: 「Hello World」 的TurboGears在URL中替換了哪些字符?

#!/usr/bin/env python3 

from wsgiref.simple_server import make_server 
from tg import expose, TGController, AppConfig 

class RootController(TGController): 
    @expose() 
    def all__things(self): 
     return "Hello world!" 

config = AppConfig(minimal=True, root_controller=RootController()) 

print("Serving on port 5000...") 
httpd = make_server('', 5000, config.make_wsgi_app()) 
httpd.serve_forever() 

當我運行app.py並參觀http://localhost:5000/all__things,我見如預期。但是,這些URL也工作:

http://localhost:5000/all--things 
http://localhost:5000/[email protected]@things 
http://localhost:5000/all$$things 
http://localhost:5000/all++things 
http://localhost:5000/all..things 
http://localhost:5000/all,,things 

以及它們的組合:

http://localhost:5000/all-_things 
http://localhost:5000/all_-things 
http://localhost:5000/[email protected] 
http://localhost:5000/[email protected] 
http://localhost:5000/[email protected] 
http://localhost:5000/[email protected]$things 

等等...

什麼是可以取代在TurboGears中的下劃線字符的完整列表網址嗎?

此外,此功能是否可以限制爲僅替換某些字符?理想情況下,我希望使用帶破折號的網址(http://localhost:5000/all--things)工作,並使用帶下劃線的網址(http://localhost:5000/all__things)或任何其他奇怪的字符無效。

回答

1

這由path_translator管理,可通過app_cfg.py中的dispatch_path_translator選項進行配置。它可以通過傳遞None或提供自定義功能來禁用。

提供的任何函數都將接收當前正在處理的部分路徑,並且必須將其歸一化。

默認路徑轉換是基於string.punctuation(見https://github.com/python/cpython/blob/c30098c8c6014f3340a369a31df9c74bdbacc269/Lib/string.py#L31

如果您有自定義路由的需求,我建議你考慮https://github.com/TurboGears/tgext.routes這可能會幫助你在更復雜的情況下,通過@route裝飾。

+0

設置'config.dispatch_path_translator = False'使程序崩潰,但'config.dispatch_path_translator = None'有效。最後我決定: 'config.dispatch_path_translator = lambda path_piece:path_piece.replace(' - ','_')如果不是'_'path_piece else''' 感謝您的幫助。 –

+0

嗯,是的,對不起,它是真/無/功能 我通過反射寫了False,與True相反:D 更新的答覆 – amol