将索引和其他路由绑定到Bottle中的单个回调时出现500错误

时间:2013-09-13 16:46:17

标签: python routes bottle

遵循本教程:

http://bottlepy.org/docs/dev/tutorial.html#request-routing

它显示了示例:

@route('/')
@route('/hello/<name>')
def greet(name='Stranger'):
    return template('Hello {{name}}, how are you?', name=name)

并声明:

  

此示例演示了两件事:您可以绑定多个路由   单个回调,您可以添加通配符到URL和访问   他们通过关键字参数。

我正在尝试使用以下代码对此进行测试,但在访问索引时遇到500错误,例如/

import bottle
import pymongo

custom = bottle

@custom.route('/')
@custom.route('/hello/<name>')
@custom.view('page2.tpl')
def index(name):

    # code

bottle.run(host='localhost', port=8082)

访问网站索引时似乎只会发生错误,例如/

索引在以下示例中不起作用,但其他两个路径都起作用。

import bottle
import pymongo

custom = bottle

@custom.route('/') # this doesn't work
@custom.route('/milo/<name>') # this works
@custom.route('/hello/<name>') # this works
@custom.view('page2.tpl')
def index(name):

    # code

bottle.run(host='localhost', port=8082)

解决方案

import bottle
import pymongo

custom = bottle

@custom.route('/')
@custom.route('/milo/<name>')
@custom.route('/hello/<name>')
@custom.view('page2.tpl')
def index(name="nowhere"):

    # code

bottle.run(host='localhost', port=8082)
除非使用前两个路由中的一个,否则输出

nowhere,在这种情况下,该值将被<name>覆盖。

1 个答案:

答案 0 :(得分:2)

调试500个错误可能很棘手,但是如果你可以让其他脚本工作,那么我的猜测是问题是因为你没有为你的索引中的name参数定义一个默认值功能。访问路径时,将调用该函数。但是如果访问/,则name参数没有值,因此在调用函数时会引发错误。

这就是您粘贴的示例def greet(name='Stranger'):的原因。 name='Stranger'设置了一个默认名称,如果没有传入名称,将使用该名称。尝试将其添加到您的函数中,看看它是否修复了它。

您可能希望在调试瓶脚本时打开debug mode,因为它会使错误消息更有帮助。