【问题标题】:How do you accept any URL in a Python Bottle server?你如何接受 Python Bottle 服务器中的任何 URL?
【发布时间】:2011-12-31 13:54:20
【问题描述】:

使用 Bottle Sehttp://bottlepy.org/docs/dev/routing.html#wildcard-filters

我想接受任何 url,然后对 url 做一些事情。

例如

@bottle.route("/<url:path>")
def index(url):
  return "Your url is " + url

这很棘手,因为 URL 中有斜线,而 Bottle 用斜线分隔。

【问题讨论】:

  • 我试过的东西:@bottle.route("/hello") 运行得很好,但 @bottle.route("/hello/") 不起作用。 ..

标签: python bottle


【解决方案1】:

在 Bottle 0.12.9 中,我这样做是为了实现可选的动态路由:

@bottle.route("/<url:re:.*>")
def index(url):
  return "Your url is " + url

【讨论】:

    【解决方案2】:

    我认为你 (OP) 一开始就走在正确的轨道上。 &lt;mypath:path&gt; 应该可以解决问题。

    我刚用 0.10 瓶试了一下,效果很好:

    ~>python test.py >& /dev/null &
    [1] 37316
    ~>wget -qO- 'http://127.0.0.1:8090/hello/cruel/world'
    Your path is: /hello/cruel/world
    

    这是我的代码。当你在你的系统上运行它时会发生什么?

    from bottle import route, run
    
    @route('<mypath:path>')
    def test(mypath):
        return 'Your path is: %s\n' % mypath
    
    run(host='localhost', port=8090)
    

    干杯!

    【讨论】:

      【解决方案3】:

      基于新的 Bottle (v0.10),使用 re 过滤器:

      @bottle.route("/<url:re:.+>")
      

      您也可以使用旧参数来做到这一点:

      @bottle.route("/:url#.+#")
      

      【讨论】:

      • 嗯,我正在尝试 ,它给了我一个 404 未找到。但是,我尝试了您的旧参数解决方案!所以这意味着我安装了旧版本的瓶子?我在这里 /Library/Python/2.6/site-packages/bottle-0.9.7-py2.6.egg/bottle.py 安装了 Bottle,它说它是 0.9.7 版,那为什么会这样呢?
      • Bottle 0.10 仅在一周前发布。瓶子 0.9 并不是很旧,但没有像我用“/”展示的过滤器。查看bottlepy.org/docs/dev/changelog.html#release-0-10 了解您可以更新到新版本的新内容。
      • 这在某些情况下会起作用,但它会阻塞包含 #$ 和类似内容的 url...
      • @starenka 这是一个 2 岁的答案。正确的做法是第一种,所以你不会有这个问题:@bottle.route("/&lt;url:re:.+&gt;")
      • @iurisilvio 是的,这就是我所说的,如果你不相信我,你自己试试吧;)
      【解决方案4】:
      @bottle.route("/hello/:myurl")
      def something(myurl):
          print myurl
          return "Your url was %s" % myurl
      

      应该没问题

      然后我会将正则表达式写入函数本身。

      或者你可以用一个新的过滤器来做,但是你必须编写一个过滤器函数并将它添加到应用程序中。

      【讨论】:

      • 我需要它来接受 URL,并且 URL 中有斜杠。例如:“localhost:8080/hello/test.com/some/page”需要完全匹配URL。
      • 完全不熟悉Bottle,但是在这种情况下myurl的价值是什么?如果它只是“test.com”,我假设其余的 url 部分也会被传递。试试 def something(*args) 看看是否所有的部分都在 args 中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      相关资源
      最近更新 更多