如何在bottlepy中呈现元组

时间:2011-11-18 15:31:57

标签: python templates bottle

我一直在使用bottlepy,我有这样的事情:

..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

在视图中我已经这样做了:

%for address date user text in comments:
      <h3>{{address}}</h3>
      <h3>{{date}}</h3>
      <h3>{{user}}</h3>
      <h3>{{text}}</h3>
%end

当我启动服务器时,错误是:

Error 500: Internal Server Error

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

Unsupported response type: <type 'tuple'>

我怎样才能将它渲染到视图中?

(对不起我的英文)

2 个答案:

答案 0 :(得分:7)

您的代码有两个问题。首先,响应不能是元组列表。它可以是字符串或字符串列表,正如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@route装饰器。

现在,您的视图代码出现问题:元组解包中的逗号丢失了。因此,您的视图(在我的情况下名为index.html)应如下所示:

%for address, date, user, text in comments:
    <h3>{{address}}</h3>
    <h3>{{date}}</h3>
    <h3>{{user}}</h3>
    <h3>{{text}}</h3>
%end

答案 1 :(得分:4)

我认为瓶子需要字符串或字符串列表,因此您可能需要转换它并进行解析。

 return str(result)

有关格式化结果的方法,请参阅http://bottlepy.org/docs/dev/tutorial_app.html

上的“格式化输出的瓶子模板”部分