如何在bottlepy中渲染元组
我一直在使用 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 个回答
4
我认为Bottle这个框架需要的是一个字符串或者字符串的列表,所以你可能需要把它转换一下并进行解析。
return str(result)
关于如何格式化结果,可以查看一下“Bottle模板格式化输出”这一部分,链接在这里:http://bottlepy.org/docs/dev/tutorial_app.html
7
你的代码有两个问题。首先,响应不能是一个元组的列表。根据彼得的建议,它可以是一个字符串或者字符串的列表,或者如果你想使用视图的话,它应该是一个包含视图变量的字典。字典的键是变量名(这些名字,比如 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