显示功能中的代码在提交

时间:2017-12-23 08:27:47

标签: python python-3.x flask

正如标题所说,我遇到了显示功能执行代码两次的问题。我很困惑为什么它在用户通过帖子提交表单后运行该功能。

我不想做的代码是运行一次,然后当用户提交if request.method == "POST":下面的代码表单时运行。

例如,如果我正在为我的网站编写路线并且具有以下代码:

@app.route("/example", methods=["GET", "POST"])
def example():
    #do some stuff beforehand ONCE
    if request.method == "POST":
       # do other stuff after the stuff above

我想要的是评论所说的内容,但它看起来更像是这样:

@app.route("/example", methods=["GET", "POST"])
def example():
    #do some stuff beforehand but TWICE
    if request.method == "POST":
       # do other stuff after the stuff above

这里最大的问题是if request.method == "POST":之上的代码修改了一个外部值,这意味着它会被更改两次,即使我将它放入局部变量。

以下是我目前正在运行的内容:

@app.route("/displayOptions", methods=["GET", "POST"])
def displayOptions():
    """ display options for selling a stock if multiple occur """
    stocks = session["identicalStocks"]
    shares = session["shares"]
    ticker = session["ticker"]
    soldStocks = db.execute("SELECT * FROM transactions WHERE stock_sold IS NOT NULL AND id = :ID", ID = session["user_id"])

    for stock in stocks:
        print(stock)
        for soldStock in soldStocks:
            if stock["transaction_number"] == soldStock["stock_sold"]:
                stock["shares"] += soldStock["shares"]

    if request.method == "POST":
        # ensure transaction number is an integer
        try:
            transactionNumber = int(request.form.get("transactionNumber"))
        except ValueError:
            return apology("Invalid transaction number")

        validTransactionNumber = False
        # ensure transaction number is correct
        for stock in stocks:
            if stock["transaction_number"] == transactionNumber:
                stockSelected = stock
                validTransactionNumber = True
                break

        if validTransactionNumber == False:
            return apology("Invalid transaction number")

        sellStock(stockSelected)

        # ensure there are a proper amount of shares to sell
        if stockSelected["shares"] < shares:
            return apology("Not enough shares to sell")

        return redirect(url_for("index"))

    return render_template("displayOptions.html", stocks = stocks)

该网站也会以stat。

重新启动

1 个答案:

答案 0 :(得分:0)

感谢John Gordon提供这个问题的答案!

如何解决:

@app.route("/example", methods=["GET", "POST"])
def example():
    if request.method == "POST":
        #do some stuff beforehand ONCE
    if request.method == "POST":
       # do other stuff after the stuff above