CS50“金融”问题,“买入”功能——哈佛CS50课程

问题描述 投票:0回答:2

目前我收到代码“购买”部分的以下错误。代码将成功运行并成功处理“购买”订单,但是 check50 返回这些错误,我无法弄清楚为什么会发生这些错误或如何解决它们。

:( buy handles fractional, negative, and non-numeric shares
    application raised an exception (see the log for more details)
:( buy handles valid purchase
    expected to find "112.00" in page, but it wasn't found

这是代码:

@app.route("/buy", methods=["GET", "POST"])
    @login_required
    def buy():
        """Buy shares of stock"""
    if request.method == "GET":
        return render_template("buy.html")
    else:
        symbol = request.form.get("symbol")
        shares = int(request.form.get("shares"))

        if not symbol:
            return apology("Must provide ticker")


        stock = lookup(symbol.upper())

        if stock == None:
            return apology("Ticker does not exist")

        if shares < 1:
            return apology("Minimum purchase is 1 share")

        transaction_value = shares * stock["price"]

        user_id = session["user_id"]
        user_cash_db = db.execute("SELECT cash FROM users WHERE id = :id", id=user_id)
        user_cash = user_cash_db[0]["cash"]

        if user_cash < transaction_value:
            return apology("Not enough funds available")

        uptd_cash = user_cash - transaction_value

        # update the SQL database
        db.execute("UPDATE users SET cash = ? WHERE id = ?", uptd_cash, user_id)

        date = datetime.datetime.now()

        db.execute("INSERT INTO transactions (user_id, symbol, shares, price, date) VALUES (?, ?, ?,                ?, ?)", user_id, stock["symbol"], shares, stock["price"], date)

        flash("Bought!")

        # redirect to main page
        return redirect("/")

和 HTML:

{% extends "layout.html" %}

  {% block title %}
    Buy
  {% endblock %}

  {% block main %}
    <h1>Buy</h1>
    <form action="/buy" method="post">
        <div class="mb-3">
            <input autocomplete="off" autofocus class="form-control mx-auto w-auto" name="symbol"     placeholder="Ticker" type="text">
        </div>
        <div class="mb-3">
            <input autocomplete="off" autofocus class="form-control mx-auto w-auto" name="shares"                                placeholder="Shares" type="number">
        </div>
        <button class="btn btn-primary" type="submit">Buy</button>
    </form>
   {% endblock %}

我尝试使用

isdigit()
方法,而不是强制共享变量为
int
,但这会在确保共享值是大于 0 的
int
时产生冲突,从而破坏代码。

python python-3.x jinja2 cs50
2个回答
0
投票

在 app.py 中,当您将股价或总价传递给“render_template()”时,请使用“usd()”函数,而在 index.html 中,请使用 {{ value | usd}} 格式显示股票价格和股票总价(按照财务提示 PSet 中的建议)


0
投票

伙计们,感谢上帝。我终于找到答案了。我的代码:index.html

{% extends "layout.html" %}

{% block title %}
    Portfolio
{% endblock %}

{% block main %}
    <h1>Portfolio</h1>
    <table class="table">
        <thead>
            <tr>
                <th scope="col">Symbol</th>
                <th scope="col">Name</th>
                <th scope="col">Shares</th>
                <th scope="col">Price</th>
                <th scope="col">TOTAL VALUE</th>
            </tr>
        </thead>
        <tbody>
            {% for stock in stocks %}
                <tr>
                    <td>{{ stock.symbol }}</td>
                    <td>{{ stock.name }}</td>
                    <td>{{ stock.total_shares }}</td>
                    <td>{{ stock.price | usd }}</td>
                    <td>{{ (stock.price * stock.total_shares) | usd }}</td>
                </tr>
            {% endfor %}
            <tr>
                <td>
                    <td colspan="4" align="right">Cash</td>
                    <td>{{ cash }}</td>
                </td>
            </tr>
            <tr>
                <td>
                    <td colspan="4" align="right">Total Value</td>
                    <td>{{ total_value }}</td>
                </td>
            </tr>
        </tbody>
    </table>
{% endblock %}

应用程序.py

索引功能:

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    user_id = session["user_id"]

    # Fetch user's stock portfolio
    stocks = db.execute("SELECT symbol, SUM(shares) as total_shares FROM transactions WHERE user_id = ? GROUP BY symbol HAVING total_shares > 0", user_id)
    cash = db.execute("SELECT cash FROM users WHERE id = ?", user_id)[0]["cash"]

    # Initial variables for total values
    total_value = cash
    grand_total = cash

    for stock in stocks:
        quote = lookup(stock["symbol"])
        stock["name"] = quote["name"]
        stock["price"] = quote["price"]
        stock["value"] = stock["price"] * stock["total_shares"]
        total_value += stock["value"]
        grand_total += stock["value"]

    return render_template("index.html", stocks=stocks, cash=usd(cash), total_value=usd(total_value), grand_total=usd(grand_total))

购买功能:

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""

    if request.method == "POST":
        # Get user inputs from the form
        symbol = request.form.get("symbol").upper()
        shares = request.form.get("shares")

        # Validate inputs
        if not symbol:
            return apology("Must give Symbol")
        elif not shares or not shares.isdigit() or int(shares) <= 0:
            return apology("Shares must be a positive integer")

        # Lookup stock information
        stock = lookup(symbol)
        if stock is None:
            return apology("Symbol does not exist")

        # Calculate transaction value
        transaction_value = int(shares) * stock["price"]

        # Get user information
        user_id = session["user_id"]
        user_cash_db = db.execute("SELECT cash FROM users WHERE id = ?", user_id)
        user_cash = user_cash_db[0]["cash"]

        # Check if the user can afford the transaction
        if user_cash < transaction_value:
            return apology("Not enough money")

        # Update user's cash
        update_cash = user_cash - transaction_value
        db.execute("UPDATE users SET cash = ? WHERE id = ?", update_cash, user_id)

        # Update transactions table
        date = datetime.datetime.now()
        db.execute(
            "INSERT INTO transactions (user_id, symbol, shares, price, date) VALUES (?, ?, ?, ?, ?)",
            user_id, stock["symbol"], shares, stock["price"], date
        )

        flash(f"Bought {shares} of {symbol} for {usd(transaction_value)}, Updated cash: {usd(update_cash)}")
        return redirect("/")

    else:
        return render_template("buy.html")

现在让我解释一下,主要问题是我们的格式使用了错误的格式。我们需要使用 usd 函数以使一切正常工作。例如,仔细查看我的索引函数和index.html。我在这里使用美元函数来处理所有事情。我使用美元函数来表示现金、total_value 和总计。我还在我的index.html中使用了usd函数:

<td>{{ stock.price | usd }}</td>
<td>{{ (stock.price * stock.total_shares) | usd }}</td>

您的值应以 number.00 或任何数字后的任何两个数字结尾。

购买:

用户购买股票后,您需要显示交易价值和更新的现金

flash(f"Bought {shares} of {symbol} for {usd(transaction_value)}, Updated cash: {usd(update_cash)}")

我已经分享了我的代码并尽可能多地解释了一切。希望它能帮助您摆脱测试错误。平安!

© www.soinside.com 2019 - 2024. All rights reserved.