【问题标题】:How to get parameters from path in Bottle?如何从Bottle中的路径获取参数?
【发布时间】:2014-06-15 07:04:57
【问题描述】:

当我执行这个网址时:

http://domain:8081/forum?id=2&page=26

使用此代码:

@route('/forum')
def display_forum():
   forum_id = request.query.id
   page = request.query.page or '1'
   return template('Forum ID: {{id}} (page {{page}})', id=forum_id, page=page)

此返回网页Forum ID: 2 (page 26)

我需要调用动态休息 url 来获得相同的结果。 url 可以是http://domain:8081/forum/2/26http://domain:8081/forum/city/place/day/hour。 不存在固定数量的参数。 我在瓶子文档中看到了一些想法,可能类似于通配符过滤器:path

【问题讨论】:

  • 你在用第二个网址http://domain:8081/forum/city/place/day/hour做什么?

标签: python rest parameters path bottle


【解决方案1】:

它不会扩展到无限的路线,但这样的事情会起作用。

@route('/forum/<first>')
def test(first):
    return first

@route('/forum/<first>/<second>')
def test(first, second):
    return first, second

@route('/forum/<first>/<second>/<third>')
def test(first, second, third):
    return first, second, third

@route('/forum/<first>/<second>/<third>/<fourth>')
def test(first, second, third, fourth):
    return first, second, third, fourth

【讨论】:

  • 不完全是他要求的。在这里,他要求在同一端点上获取 GET 参数。
【解决方案2】:

使用参数

@route ('/forum/forum_id=:forum_id&page=:page')
def display_forum(forum_id,page):
   forum_id = request.query.id
   page = request.query.page or '1'
   return template('Forum ID: {{id}} (page {{page}})', id=forum_id, page=page)

【讨论】:

  • @ron.rothman 我只是在他的代码中添加了参数,如果上面的代码可以工作,那么这也可以工作,因为我已经用参数进行了测试
  • 我认为您将查询参数(在? 之后)与 Bottle 的动态路径参数混淆了。您刚刚将 OP 的查询参数转换为路线的模式匹配部分,这是 (a) 奇怪的,并且 (b) 不是 OP 所要求的。
猜你喜欢
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 2020-05-28
相关资源
最近更新 更多