hiboshi
V2EX  ›  Flask

flask 奇怪问题

  •  
  •   hiboshi · Jun 3, 2015 · 3435 views
    This topic created in 4022 days ago, the information mentioned may be changed or developed.

    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 replies    2015-06-04 13:57:06 +08:00
    lilydjwg
        1
    lilydjwg  
       Jun 3, 2015
    因为 entry 没有那些属性。神奇的 jinja2 会在这种情况下将之渲染成空字符串。

    entry 是从数据库里取到的。默认是 tuple 类型,如果使用 DictCursor 的话会是字典类型。除非你自己写个 cursor 类,否则无论如何不会是 ORM 那样的带属性的对象。
    hiboshi
        2
    hiboshi  
    OP
       Jun 3, 2015
    @lilydjwg 有现成的cursor 类么,你们一般是怎么把 元组 转为 jinja2 可用的?
    lilydjwg
        3
    lilydjwg  
       Jun 3, 2015
    @hiboshi 我不太了解 jinja2。用过 ORM。
    也许 jinja2 能自动把属性访问变换成取字典键值?你试试 DictCursor,MySQLdb 应该有。
    hiboshi
        4
    hiboshi  
    OP
       Jun 3, 2015
    @lilydjwg 好的谢谢 我试试
    itommy
        6
    itommy  
       Jun 3, 2015
    上面链接的评论里面说了 @lilydjwg lily酱 提到的 DictCursor
    hiboshi
        7
    hiboshi  
    OP
       Jun 3, 2015
    @itommy
    @lilydjwg
    已经解决
    import MySQLdb.cursors
    conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="web",cursorclass=MySQLdb.cursors.DictCursor)
    sivacohan
        8
    sivacohan  
    PRO
       Jun 4, 2015 via Android
    你看一下你这么connect好像是没有连接池的吧?
    建议外面包个连接池
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1306 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 17:08 · PVG 01:08 · LAX 10:08 · JFK 13:08
    ♥ Do have faith in what you're doing.