【问题标题】:How to render tuples in bottlepy如何在bottlepy中渲染元组
【发布时间】:2011-11-18 15:31:56
【问题描述】:

我一直在使用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'>

如何将其渲染到视图中?

(对不起我的英语)

【问题讨论】:

    标签: python templates bottle


    【解决方案1】:

    您的代码有两个问题。首先,响应不能是元组列表。正如 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
    

    【讨论】:

    • 我有视图和路由装饰器,“..code..”是它们的缩写。我的错误是“return cmets”和逗号。非常感谢您的帮助!我是 python 新手,有些东西还不清楚..
    【解决方案2】:

    我相信瓶子需要一个字符串或字符串列表,因此您可能需要对其进行转换和解析。

     return str(result)
    

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

    上的“Bottle Template To Format The Output”部分

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 2021-11-20
      • 2019-05-14
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      相关资源
      最近更新 更多