如何在bottlepy中呈现元组

2024-04-19 01:59:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在用瓶装水,我有这样一种感觉:

..code..
comments = [(u'34782439', 78438845, 6, u'hello im nick'), 
(u'34754554', 7843545, 5, u'hello im john'), 
(u'332432434', 785345545, 3, u'hello im phil')] 

return comments

在我看来,我已经做到了:

^{pr2}$

启动服务器时,错误是:

Error 500: Internal Server Error

Sorry, the requested URL http://localhost:8080/hello caused an error:

Unsupported response type: <type 'tuple'>

我怎样才能把它渲染到视图中呢?在

(对不起我的英语)


Tags: helloreturntype错误codeerrorjohncomments
2条回答

你的代码有两个问题。首先,响应不能是元组的列表。它可以是一个字符串或字符串列表,正如Peter所建议的那样,或者,如果您想使用视图,它可以(并且应该)是视图变量的字典。键是变量名(这些名称,如comments,在视图中可用),值是任意对象。在

因此,可以将处理程序函数重写为:

@route('/')
@view('index')
def index():
    # code
    comments = [
        (u'34782439', 78438845, 6, u'hello im nick'), 
        (u'34754554', 7843545, 5, u'hello im john'), 
        (u'332432434', 785345545, 3, u'hello im phil')]
    return { "comments": comments }

注意@view和{}装饰符。在

现在,视图代码中出现了一个问题:元组解包中缺少逗号。因此,您的视图(在我的例子中命名为index.html)应该如下所示:

^{pr2}$

我相信bottle需要一个字符串或一个字符串列表,所以您可能需要转换它并进行解析。在

 return str(result)

对于格式化结果的方法,请查看位于http://bottlepy.org/docs/dev/tutorial_app.html处的“瓶子模板以格式化输出”部分

相关问题 更多 >