用于 Sinatra 风格 URL 路由的 Python 等效 Ruby 块

发布于 2024-10-18 23:10:39 字数 561 浏览 1 评论 0原文

有没有办法在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

凝望流年 2024-10-25 23:10:39

正如你所说,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.

不一样的天空 2024-10-25 23:10:39

另一种方法是使用元类,就像在 webpy 的 web.autoapplication 中完成的那样,源代码

Another way would be using metaclasses, as it is done in webpy's web.autoapplication, source code for that.

无声情话 2024-10-25 23:10:39

那么,对于你的第二个问题“是否有任何理由表明这可能是不可取的?”。

  • 有了命名函数,就可以执行 url_for(some_function) 的操作,从而可以轻松地重构网站。
  • 命名函数允许测试、文档字符串等。

So, to your second question of 'And are there any reasons why this might not be desirable?'.

  • Having named functions makes it possible to do things url_for(some_function), which makes it easy to restructure the site.
  • named functions allow for testing, docstrings, etc.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文