V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hiboshi
V2EX  ›  Flask

flask 奇怪问题

  •  
  •   hiboshi · 2015-06-03 21:53:53 +08:00 · 2774 次点击
    这是一个创建于 3221 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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

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

    entry 是从数据库里取到的。默认是 tuple 类型,如果使用 DictCursor 的话会是字典类型。除非你自己写个 cursor 类,否则无论如何不会是 ORM 那样的带属性的对象。
    hiboshi
        2
    hiboshi  
    OP
       2015-06-03 22:48:45 +08:00
    @lilydjwg 有现成的cursor 类么,你们一般是怎么把 元组 转为 jinja2 可用的?
    lilydjwg
        3
    lilydjwg  
       2015-06-03 22:52:55 +08:00
    @hiboshi 我不太了解 jinja2。用过 ORM。
    也许 jinja2 能自动把属性访问变换成取字典键值?你试试 DictCursor,MySQLdb 应该有。
    hiboshi
        4
    hiboshi  
    OP
       2015-06-03 23:05:51 +08:00
    @lilydjwg 好的谢谢 我试试
    itommy
        6
    itommy  
       2015-06-03 23:12:58 +08:00
    上面链接的评论里面说了 @lilydjwg lily酱 提到的 DictCursor
    hiboshi
        7
    hiboshi  
    OP
       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
        8
    sivacohan  
       2015-06-04 13:57:06 +08:00 via Android
    你看一下你这么connect好像是没有连接池的吧?
    建议外面包个连接池
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1553 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:00 · PVG 01:00 · LAX 10:00 · JFK 13:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.