【问题标题】:bottle.py URL routing & reverse howto?bottle.py URL 路由和反向操作?
【发布时间】:2014-10-10 16:44:49
【问题描述】:

示例 Bottle.py 代码:

@route('/show_<name>')
def show(name):
   return ''

我的问题是:

  1. 给定一个 URL,我们如何获取视图函数?例如。 URL是/show_magic,我需要知道show()函数负责这个请求URL

  2. 给定一个路由(不是Router!!)和参数,如何获取URL?例如我需要一个名为 reverse 的函数 reverse(default_app().routes[0], name='me') == '/show_me'

【问题讨论】:

    标签: python url-routing bottle


    【解决方案1】:

    您可能需要考虑命名路线

    @route('/show_<item_name>', name='item_show')
    def show(item_name):
       return ''
    

    现在给定路由名称和参数如何获取 URL?我们使用 get_url

    get_url('item_show', item_name='my_item')
    

    http://nongraphical.com/2012/08/using-bottle-py-in-production/

    【讨论】:

      【解决方案2】:

      对于您的第一个问题,请使用Bottle.match。给定一个path(即'/show_magic')和methodGETPOST或其他),以下将返回一个包含Route对象及其参数的元组:

      default_app().match({'PATH_INFO': path, 'REQUEST_METHOD': method})
      

      调用的函数是Route对象的callbackcall属性。

      对于第二个问题,使用路由器的build 方法与路由的rule 和kwargs:

      default_app().router.build(route.rule, name='me')
      

      这似乎没有记录,但它确实有效。

      【讨论】:

      • 谢谢,看了你的代码和瓶子的源代码,真的可以。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 2016-12-09
      • 2013-12-14
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多