python - 路由到基于字符串的方法

标签 python routes tornado python-routes

我试图在 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/

相关文章:

python - 使用python输出到两个不同的控制台

python - django-facebook 内部代码说找不到 facebook_id

php - silex 路线不工作

django - 什么是与Django搭配使用的最佳socket.io服务器-gevent或tornadio2?

python - 为什么在 CUDA 内核中没有断点的情况下执行相同的程序时,cuda-gdb 比 gdb 慢很多?

python - 如果函数的参数是语句中的字符串,如何编写函数的参数?

node.js - 如何在 Express 路由中设置 Next.js 渲染?

ruby-on-rails - rails rake 路线他们来自哪里

python - Json响应错误: response null?

python - 如何为 python tornado 应用程序编写单元测试?