首页 > 解决方案 > 需要帮助使用 Flask 应用程序访问 Jinja 中的 Python 字典值

问题描述

这是我的 Flask Python 应用程序。

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""

    holdings = db.execute("SELECT symbol,SUM(shares),price FROM purchases GROUP BY symbol HAVING id = ?",session["user_id"])

    return render_template("index.html",holdings=holdings)

这是我的 HTML 索引文件

{% extends "layout.html" %}

{% block title %}
    Log In
{% endblock %}

{% block main %}
<table class="table table-striped">
        <thead>
            <tr>
                <th>Symbol</th>
                <th>Name</th>
                <th>Shares</th>
                <th>Price</th>
                <th>TOTAL</th>
            </tr>
        </thead>
        <tbody>
            {% for trade in holdings %}
                <tr>
                    <td>{{trade.symbol}}</td>
                    <td>{{trade.SUM(shares)}}</td>
                    <td>{{trade}}</td>
                    <td>{{trade.price}}</td>
                    <td>$278.94</td>
                </tr>
            {% endfor %}
            <tr>
                <td colspan="4">CASH</td>
                <td>$9,589.93</td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="4"></td>
                <td>{{total}}</td>
            </tr>
        </tfoot>
    </table>
{% endblock %}

持有以字典格式返回行列表,如下所示{'symbol': 'aapl', 'SUM(shares)': 1038, 'price': 137.27}:这适用于每一行。

问题


第一季度

当我尝试访问第二个字典键SUM(shares)时它不起作用并弹出错误

( <td>{{trade.SUM(shares)}}</td> jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'SUM')

当我尝试使用围绕SUM(shares)此的报价时会弹出

<td>{{trade.'SUM(shares)'}}</td> jinja2.exceptions.TemplateSyntaxError: expected name or number

我正在使用 CS50 IDE。

为什么会这样?我该如何解决?


第二季度

为了访问字典值,dictionary["key"]我没有像在 Python 中那样做,而是dictionary.key在 Jinja 中做。这是普通的 Jinja 还是课程中经过特殊修改的 Jinja?

标签: sqlflaskjinja2cs50

解决方案


编辑:由于包含可以以多种方式解释的字符的键值SUM(shares),您需要切换到your_dict['your_key']访问语法而不是“点”访问语法:

            {% for trade in holdings %}
                <tr>
                    <td>{{ trade["symbol"] }}</td>
                    <td>{{ trade["SUM(shares)"] }}</td>
                    <td>{{ trade["price"] }}</td>
                </tr>

推荐阅读