【问题标题】:Access these dictionary values in flask template在烧瓶模板中访问这些字典值
【发布时间】:2017-01-02 15:41:45
【问题描述】:

我的模板正在输出以下内容。它不拉入任何查询值,但拉入page loads finedoesnt fail,但它不显示任何values

我在mysqlmonitor 中仔细检查了query,它提取了3 条记录。

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

templates/index.html我有:

    {% for blogpost in blogposts %}
        <li><a href="http://blog.mysite.com/wordpress/{{blogpost[2]}}/{{blogpost[3]}}/{{blogpost[1]}}">{{blogpost[0]}}</a></li>
    {% else %}
        <li>no blog posts right now...</li>
    {% endfor %}

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"}]

如何在我的 flask template 中访问这些数据?

非常感谢!

【问题讨论】:

    标签: python mysql templates flask


    【解决方案1】:

    尝试找出发送到模板的内容。将print(blogposts) 添加到电子邮件功能 - 就在if request.method == 'POST': 行下方,看看它为您提供了哪些信息。

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

    【讨论】:

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

      在 index.html 中

      {% if data %}
      <h1>{{data['id']}}</h1>
      <h1>{{data['name']}}</h1>
      {% endif%}
      

      或者..你也可以迭代

      <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 %}
      

      【讨论】:

      • value = "{{ data['full_name']}}" 对我不起作用。但是 value = "{{ data}}" 打印 jinja2 模板中的所有数据
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 2020-11-08
      • 2021-10-17
      相关资源
      最近更新 更多