2016-11-18 19 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