如何在Python Bottle服务器中接受任意URL?

15 投票
4 回答
8535 浏览
提问于 2025-04-17 06:31

使用Bottle框架的文档链接:这里

我想接受任何网址,然后对这个网址做点什么。

比如:

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

这有点棘手,因为网址里面有斜杠,而Bottle会根据斜杠来分割网址。

4 个回答

1

在Bottle 0.12.9版本中,我这样做来实现可选的动态路由:

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

我觉得你一开始的思路是对的。<mypath:path> 应该可以解决问题。

我刚刚在 bottle 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)

祝好运!

18

根据新的Bottle版本(v0.10),可以使用正则表达式过滤器:

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

你也可以使用旧的参数来实现这个功能:

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

撰写回答