在Flask温度中访问这些字典值

2024-09-27 21:27:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我的模板正在输出以下内容。它不拉入任何查询值,而是page loads fine和{},但它不显示任何{}。在

我再次检查了query中的query,它会按需要提取3条记录。在

 <li><a href="http://blog.mysite.com/wordpress///"></a></li>

templates/index.html我有:

^{pr2}$

app.py有这个:

import pymysql.cursors
app = Flask(__name__)
connection = pymysql.connect(host='localhost', user='myuser', port=3306, password='mypass', db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

@app.route('/', methods=('GET', 'POST'))
def email():
    form = EmailForm()

    curs = connection.cursor()

    curs.execute("SELECT post_title, post_name, YEAR(post_date) as YEAR, MONTH(post_date) as MONTH FROM mydb.wp_posts WHERE post_status='publish' ORDER BY RAND() LIMIT 3")


    blogposts = curs.fetchall()
    if request.method == 'POST':
        return render_template('index.html', form=form, blogposts=blogposts)
if __name__ == '__main__':
    app.run()

更新我认为我的for()工作不正常,因为当我在template中更新时,我得到的所有数据如下:

 [{u'MONTH': 12, u'YEAR': 2016, u'post_name': u'data is here', u'post_title': u'data is here'}, 
{u'MONTH': 12, u'YEAR': 2016, u'post_name': u'data is here', u'post_title': u"data is here"}]

如何访问我的烧瓶中的数据template?在

非常感谢你!在


Tags: nameformappdataheretitleistemplate
2条回答

尝试找出要发送到模板的内容。在email函数中添加print(blogposts),就在if request.method == 'POST':行的下面,看看它能给你提供什么信息。在

如果blogposts是一个字典列表,那么您不能通过数字访问它们。您需要使用密钥的名称。例如,您需要将blogpost[0]更改为blogpost['name']。对于Flask的模板,您还可以使用点表示法,因此blogpost的名称将变成blogpost.name。在

   @app.route('/get', methods=['POST','GET'])
   def requestCustomerDataFromTestForm():
       data={'id':1, 'name':'Josh'}
       return render_template("index.html", data = data)

在索引.html在

^{pr2}$

或者。。你也可以迭代

<table class="table table-striped" >
    <thead>
      <tr>
        <th scope="col">id</th>
        <th scope="col">name</th>
      </tr>
    </thead>
    <tbody>
{% for key, value in data.items() %}
  <tr>
    <th scope="row">{{ key }}</th>
    <td>{{ value }}</td>
  </tr>
  {% endfor %}
</tbody>
</table>

或者,显示所有数据及其索引

{% if data %}

<p>{{data}}</p>
{% endif %}

相关问题 更多 >

    热门问题