flask 奇怪问题

2015-06-03 21:53:53 +08:00
 hiboshi

conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="web")
cursor = conn.cursor()
cursor.execute("select * from weather")
entries = cursor.fetchall()

return render_template('test.html', entries=entries)

{% for entry in entries %}
<li><h2>{{ entry.id }}</h2>{{ entry.dara_from }}
{% else %}
<li><em>Unbelievable. No entries here so far</em>
{% endfor %}

为什么页面查看源码搜这样的

<li><h2></h2>

<li><h2></h2>

<li><h2></h2>

<li><h2></h2>

<li><h2></h2>

<li><h2></h2>

<li><h2></h2>

<li><h2></h2>

也就是说 字段没有显示,但是 列数是对的。我明明写的是 select * from

2799 次点击
所在节点    Flask
8 条回复
lilydjwg
2015-06-03 21:58:42 +08:00
因为 entry 没有那些属性。神奇的 jinja2 会在这种情况下将之渲染成空字符串。

entry 是从数据库里取到的。默认是 tuple 类型,如果使用 DictCursor 的话会是字典类型。除非你自己写个 cursor 类,否则无论如何不会是 ORM 那样的带属性的对象。
hiboshi
2015-06-03 22:48:45 +08:00
@lilydjwg 有现成的cursor 类么,你们一般是怎么把 元组 转为 jinja2 可用的?
lilydjwg
2015-06-03 22:52:55 +08:00
@hiboshi 我不太了解 jinja2。用过 ORM。
也许 jinja2 能自动把属性访问变换成取字典键值?你试试 DictCursor,MySQLdb 应该有。
hiboshi
2015-06-03 23:05:51 +08:00
@lilydjwg 好的谢谢 我试试
itommy
2015-06-03 23:11:41 +08:00
itommy
2015-06-03 23:12:58 +08:00
上面链接的评论里面说了 @lilydjwg lily酱 提到的 DictCursor
hiboshi
2015-06-03 23:26:32 +08:00
@itommy
@lilydjwg
已经解决
import MySQLdb.cursors
conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="web",cursorclass=MySQLdb.cursors.DictCursor)
sivacohan
2015-06-04 13:57:06 +08:00
你看一下你这么connect好像是没有连接池的吧?
建议外面包个连接池

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/195920

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX