0

Following this tutorial:

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

It shows the example:

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

And states:

This example demonstrates two things: You can bind more than one route to a single callback, and you can add wildcards to URLs and access them via keyword arguments.

I'm trying to test this with the following code but I am getting a 500 error when accessing the index eg /.

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)

The error only seems to occur when accessing the site's index, eg /.

The index does not work in the following example, but the other two routes do.

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)

Solution

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 is output unless one of the first two routes are used, in which case that value is overwritten by whatever <name> is.

4

1 回答 1

2

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

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

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

于 2013-09-13T16:49:51.743 回答