我试图在 Python 中调用一个基于字符串的方法,类似于 Tornado 基于 URL 路由请求的方式。因此,例如,如果我有字符串“/hello”,我想在某个类中调用方法“hello”。我一直在研究 Python 路由并提出了以下解决方案:
from routes import Mapper
class Test():
def hello(self):
print "hello world"
map = Mapper()
map.connect(None, '/hello', controller=Test(), action='hello')
match = map.match("/hello")
if match != None:
getattr(match['controller'], match['action'])()
但是我想添加将部分字符串作为参数传递给方法的功能。因此,例如,对于字符串“hello/5”,我想调用 hello(5)
(同样与 Tornado 的路由非常相似)。这应该适用于任意数量的参数。有人对此有好的方法吗?是否可以在不是请求 URL 的字符串上使用 Tornado 的路由功能?
最佳答案
首先,最好知道制作这样一个“本地”路由系统的动机、用例和初始任务是什么。
根据您的示例,一种方法是实际构建您自己的东西。
这是一个非常基本的例子:
class Test():
def hello(self, *args):
print args
urls = ['hello/', 'hello/5', 'hello/5/world/so/good']
handler = Test()
for url in urls:
parts = url.split('/')
method = parts[0]
if hasattr(handler, method):
getattr(handler, method)(*parts[1:])
打印:
('',)
('5',)
('5', 'world', 'so', 'good')
您还可以使用正则表达式将部分 url 保存为命名组或位置组。例如,看看如何 django , python-routes正在做。
希望对您有所帮助。
关于python - 路由到基于字符串的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22278536/