【问题标题】:Python Bottle template issue: AttributeError("'dict' object has no attribute 'city'",)Python Bottle 模板问题:AttributeError("'dict' object has no attribute 'city'",)
【发布时间】:2013-12-31 18:12:58
【问题描述】:

作为一个学习项目,我将 MongoDB 与 Bottle 一起用于 Web 服务。我想要做的是从 MongoDB 中获取结果并将它们显示在模板中。这是我想要的模板输出:

output.tpl
<html><body>
%for record in records:
   <li>{{record.city}} {{record.date}}
%end
</body></html>

我可以把数据拉出来没问题:

result = db.records.find(query).limit(3)
return template('records_template', records=result)

但这根本没有输出 - 一些调试告诉我结果是某种游标:

<pymongo.cursor.Cursor object at 0x1560dd0>

所以我尝试将其转换为模板想要的内容:

result = db.records.find(query).limit(3)
viewmodel=[]
for row in result:
  l = dict()
  for column in row:
    l[str(column)]=row[column]
  viewmodel.append(l)
return template('records_template', records=viewmodel)

调试显示我的视图数据看起来不错:

[{'_id': ObjectId('4fe3dfbc62933a0338000001'),
  'city': u'CityName',
  'date': u'Thursday June 21, 2012'},
 {'_id': ObjectId('4fe3dfbd62933a0338000088')
  'city': u'CityName',
  'date': u'Thursday June 21, 2012'},
 {'_id': ObjectId('4fe3dfbd62933a0338000089')
  'city': u'CityName',
  'date': u'Thursday June 21, 2012'}]

但这是我得到的回应。任何想法为什么?

AttributeError("'dict'对象没有属性'city'",)

编辑:我添加了有关 l[str(column)]=row[column] 的内容,以将字典键转换为非 unicode 字符串,以防万一出现问题,但这似乎并不重要。

【问题讨论】:

  • 您是否尝试过使用字典语法?示例:{{record['city']}} {{record['date']}}
  • 只是回到你原来的发现,你必须在发送到模板之前将它从光标转换成字典吗?

标签: python mongodb bottle


【解决方案1】:

您需要使用字典语法来查找属性:

{{record['city']}} {{record['date']}}

【讨论】:

    【解决方案2】:
    result = db.records.find(query).limit(3)
    viewmodel=[]
    for row in result:
      l = dict()
      for column in row:
        l[str(column)]=row[column]
      viewmodel.append(l)
    return template('records_template', records=viewmodel)
    

    可以概括为:

    result = db.records.find(query).limit(3)
    return template('records_template', records=list(result))
    

    Python 的美丽...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-01
      • 2018-08-26
      • 2021-01-08
      • 2018-02-05
      • 2019-09-23
      • 2020-04-26
      • 2020-11-21
      • 1970-01-01
      相关资源
      最近更新 更多