用于 Sinatra 风格 URL 路由的 Python 等效 Ruby 块
有没有办法在 Python 中重新创建 Sinatra 的 URL 路由?有什么理由可以解释为什么这可能是不可取的吗?
来自 Sinatra:
get '/' do
'Hello world!'
end
来自 Flask(使用装饰器进行路由):
@app.route("/")
def hello():
return "Hello World!"
Sinatra 通过 Ruby 块实现了这种简洁性:
def get(path, opts={}, &block)
conditions = @conditions.dup
route('GET', path, opts, &block)
@conditions = conditions
route('HEAD', path, opts, &block)
end
我认为 Python 没有与 Ruby 块完全相同的功能,但有一些方法可以重新创建功能。这怎么办?
Is there a way of recreating Sinatra's URL routing in Python? And are there any reasons why this might not be desirable?
From Sinatra:
get '/' do
'Hello world!'
end
From Flask (using decorators for routing):
@app.route("/")
def hello():
return "Hello World!"
Sinatra achieves this succinctness through Ruby blocks:
def get(path, opts={}, &block)
conditions = @conditions.dup
route('GET', path, opts, &block)
@conditions = conditions
route('HEAD', path, opts, &block)
end
I gather that Python does not have an exact equivalent of Ruby blocks, but that there are ways of recreating the functionality. How might this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如你所说,Python 没有像 ruby 块这样的东西。装饰器是常用的路由解决方案。另一种方法是创建一个包含路由的列表/字典,但由于您似乎希望路由定义位于底层代码旁边,因此您需要使用装饰器方法。
As you said, Python doesn't have something like ruby blocks. Decorators are the commonly used solution for routing. The other way would be creating a list/dict containing the routes but since you seem to want the route definitions next to the underlying code, the decorator way is what you'll want to use.
另一种方法是使用元类,就像在 webpy 的 web.autoapplication 中完成的那样,源代码。
Another way would be using metaclasses, as it is done in webpy's web.autoapplication, source code for that.
那么,对于你的第二个问题“是否有任何理由表明这可能是不可取的?”。
url_for(some_function)
的操作,从而可以轻松地重构网站。So, to your second question of 'And are there any reasons why this might not be desirable?'.
url_for(some_function)
, which makes it easy to restructure the site.