bottlepy路由匹配任意URL并排除特定情况
我正在用Bottle框架为每个请求写一个模板。也就是说,无论是访问localhost,还是localhost/mypage,或者localhost/mypage/about,都会调用同一个模板。我在这里查了一下,发现了一些很好的例子,能够匹配所有的URL,像这样:
from bottle import route, run, template, static_file
@route("/<url:re:.+>")
def hello(url):
return template('page_template', url=url)
@route('/static/<filepath:path>', name='static')
def server_static(filepath):
return static_file(filepath, root='static')
run()
我有几个问题: 1) 它不匹配根目录。所以如果我输入“localhost”,它就不工作了。 2) 由于有静态文件,我还有一个专门处理静态文件的路由。所以如果我输入localhost/static/page,它也不会返回“hello world”。
我觉得我需要修改正则表达式(/<:re:.+>)来解决这两个问题。任何帮助都非常感谢,
@Michael
1 个回答
0
好消息:你可以很简单地“叠加”路由。只需要这样做:
@route("/")
@route("/<url:re:.+>")
def hello(url):
return template('page_template', url=url)
这样的话,根路由就会和你现有的正则路由一样处理。
至于重叠的路由,根据文档的说明,动态路由会按照你定义的顺序来评估。