sql - 需要帮助使用 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?
解决方案
编辑:由于包含可以以多种方式解释的字符的键值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>
推荐阅读
- ruby-on-rails - Rails,如何对集合进行排序,最后保持特定值
- php - 命令在 mongodb 指南针中有效,但在 php 中无效
- aerospike - How to query bin level LUT on Aerospike 5.5?
- node.js - Discord bot 只注册第一个斜杠命令
- microsoft-cognitive - Azure 说话人识别区域限制
- c# - C# WinAppCalculator 到 WebAppCalculator
- python - 二元交叉熵计算中的 pos_weight
- ubuntu - 在lfs中不知不觉跳过了一步
- javascript - 很少有字段没有使用 redux 表单中的初始值进行更新
- java - 在 Java 中转换为 List 结果