首页 > 解决方案 > 我越来越接近于找出 CS50 中 Finance 的索引部分,但我的表无法正常工作

问题描述

我想我正确地创建了我的字典,然后将它输入 render_template 并显示我的索引,但有些不对劲。这是我的 index() 的代码:


@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    #dictionary to feed data into index
    temp={}
    #Select from trades all stocks held by this user
    ss = db.execute("SELECT SUM(shares), symbol FROM trades WHERE id=? GROUP BY symbol", session["user_id"])
    print(ss)
    #lookup current price for each stock and create index of all stocks held
    for row in ss:
        data=lookup(row["symbol"])
        totval=row["SUM(shares)"]*data["price"]
        temp1={"symbol":data["symbol"], "name":data["name"], "shares":row["SUM(shares)"], "price":data["price"], "total value":totval}
        temp[data["symbol"]]=temp1

    print(temp)

    return render_template("index.html", temp=temp[data["symbol"]])

这是 index.html 的代码。是的,我仍然需要添加现金和现金 + 总价值,一旦我让桌子正常运行,我就会这样做。

{% extends "layout.html" %}

{% block title %}
    Index
{% endblock %}

{% block main %}
   <h1>Stock Holdings</h1>
    <table>
        <thead>
            <tr>
                <th>Symbol</th>
                <th>Name</th>
                <th>Shares</th>
                <th>Price</th>
                <th>Total Value</th>
            </tr>
        </thead>
        <tbody>
            {% for row in temp %}
                <tr>
                    <td>{{ temp["symbol"] }}</td>
                    <td>{{ temp["name"] }}</td>
                    <td>{{ temp["shares"] }}</td>
                    <td>{{ temp["price"] }}</td>
                    <td>{{ temp["totval"] }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

{% endblock %}

现在这是我的 print(temp) 用于输入 index.html 的字典:

{'AAPL': {'symbol': 'AAPL', 'name': 'Apple Inc', 'shares': 1, 'price': 131.46, 'total value': 131.46}, 'IBM': {'symbol': 'IBM', 'name': 'International Business Machines Corp.', 'shares': 3, 'price': 141.88, 'total value': 425.64}}

这是我的应用程序中显示的索引:

Stock Holdings
Symbol  Name    Shares  Price   Total Value
IBM International Business Machines Corp.   3   141.88  
IBM International Business Machines Corp.   3   141.88  
IBM International Business Machines Corp.   3   141.88  
IBM International Business Machines Corp.   3   141.88  
IBM International Business Machines Corp.   3   141.88  

所以它打印出字典的最后一行 5 次并且不打印出最后一列“总价值”,但是当我打印字典时你可以看到它就在那里。这是我第一次使用桌子,我意识到我没有正确地喂东西,但不知道如何修复。谢谢。

标签: indexingcs50finance

解决方案


推荐阅读