【问题标题】:Doing cs50 Finance and "buy" is generating a run time error做 cs50 Finance 和“购买”会产生运行时错误
【发布时间】:2021-04-17 17:13:29
【问题描述】:

我的错误在于我调整现金以反映购买股票的情况。命令行错误是:RuntimeError: near "['user_id']": 语法错误。我在代码行中正确使用了“”和“”。另外在命令行中我得到了:错误:/buy [POST] 上的异常,我不明白。如果您有任何想法,请告诉我。谢谢。

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    if request.method == "POST":
        # Ensure ticker was submitted
        if not request.form.get("symbol"):
            return apology("must input stock symbol")


        # Get symbol and make sure it exists
        symbol = lookup(request.form.get("symbol"))

        if not symbol:
            return apology("symbol does not exist")


        # Ensure shares entered greater than zero
        number=int(request.form.get("shares"))
        if number <= 0:
            return apology("must enter number of shares to buy")

        # set up dict to store purchase info: name, price, symbol
        quote = lookup(request.form.get("symbol"))


        # Dollars needed for purchase

        pcash=number * quote["price"]

        # Is there enough cash in account to purchase
        ecash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])
        if pcash >= ecash[0]["cash"]:
            return apology("Not enough cash to buy that amount of stock")

        # Record buy in trades.db for user-id
        x=datetime.datetime.now()
        db.execute("INSERT INTO trades (datetime, symbol, shares, price, total, id) VALUES(?, ?, ?, ?, ?, ?)", x, quote["symbol"], number, quote["price"], pcash, session["user_id"])


        # Adjust cash to reflect purchase
        y=ecash[0]["cash"]-pcash
        db.execute("UPDATE users SET cash=? WHERE id=session['user_id']", y)

        # Redirect user to home page
        return redirect("/")

     # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("buy.html") 

【问题讨论】:

  • 请包含完整的错误

标签: cs50 finance


【解决方案1】:

UPDATE users SET cash=? WHERE id=session['user_id'] 是 sqlite 试图执行的查询。 sqlite 不知道session['user_id'](它是一个python 变量)。该方法将接受多个占位符(即?)。为 WHERE 子句使用占位符,并将值作为附加参数发送。

【讨论】:

  • 正确!谢谢。
猜你喜欢
  • 1970-01-01
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
相关资源
最近更新 更多