简体   繁体   中英

how to add variable in a action post Flask and Python

I m still continue in my flask project and my issue is when I click on sell button, I ve an error. I think is due to the fact that the post action send invalid url. It send POST /sell1 HTTP/1.1

and I think It should send POST /sell1/AAPL HTTP/1.1 (AAPL is value of variable symbol in my code for example) thanks for help.

error I get is: 404 not found

my code:

sell1.html:

{% block main %}
    <form action="/sell1/" method="post">
        <div class="form-group">
            <text id="stock" name="symbol">
                {{ stocks }}
            </text>
            , owned
            <text id="nbr" name="amount">
                 {{ nbr }}
            </text>
        </div>
        <div class="form-group">
            <input min="1" autocomplete="off" autofocus class="form-control" name="amount" placeholder="Amount" type="number">
        </div>
        <button id="submit" class="btn btn-primary" type="submit">Sell</button>
    </form>
{% endblock %}

app.py

def sell1(stock):
    """Sell shares of stock"""

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        # collect relevant informations

        amount = int(request.form.get("amount"))
        symbol = request.form.get("symbol")
        price = lookup(symbol)["price"]
        value = round(price * float(amount))

        # Update stocks table
        amount_before = db.execute("SELECT amount FROM stocks WHERE user_id = :user AND symbol = :symbol",
                                   symbol=symbol, user=session["user_id"])[0]['amount']
        amount_after = amount_before - amount

        # delete stock from table if we sold every unit we had
        if amount_after == 0:
            db.execute("DELETE FROM stocks WHERE user_id = :user AND symbol = :symbol",
                       symbol=symbol, user=session["user_id"])

        # stop the transaction if the user does not have enough stocks
        elif amount_after < 0:
            return apology("That's more than the stocks you own")

        # otherwise update with new value
        else:
            db.execute("UPDATE stocks SET amount = :amount WHERE user_id = :user AND symbol = :symbol",
                       symbol=symbol, user=session["user_id"], amount=amount_after)

        # calculate and update user's cash
        cash = db.execute("SELECT cash FROM users WHERE id = :user",
                          user=session["user_id"])[0]['cash']
        cash_after = cash + price * float(amount)

        db.execute("UPDATE users SET cash = :cash WHERE id = :user",
                   cash=cash_after, user=session["user_id"])

        # Update history table
        db.execute("INSERT INTO transactions(user_id, symbol, amount, value) VALUES (:user, :symbol, :amount, :value)",
                   user=session["user_id"], symbol=symbol, amount=-amount, value=value)

        # Redirect user to home page with success message
        flash("Sold!")
        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:

        # Add Symbol

        # query database with the transactions history
        rows = db.execute("SELECT symbol, amount FROM stocks WHERE (user_id = :user AND symbol = :stock)",
                          user=session["user_id"], stock=stock)

        Nbr = rows[0]['amount']
        return render_template("sell1.html", stocks=stock, nbr=Nbr)

I find a solution with javascript:

    <form id="actionform"  method="post" onsubmit="get_stock_quote()">
        <div class="form-group">
            <input type="text" id="stock" name="symbol" value="{{ stocks }}">

            , owned
            <text id="nbr" name="amountbefore">
                 {{ nbr }}
            </text>
        </div>
        <div class="form-group">
            <input min="1" autocomplete="off" autofocus class="form-control" name="amount" placeholder="Amount" type="number">
        </div>
        <button id="submit" class="btn btn-primary" type="submit">Sell</button>
    </form>

    <script language="javascript" type="text/javascript">
    function get_stock_quote()
    {
        var form = document.getElementById('actionform')
        var symbol = document.getElementById('symbol').value
        var action_src = "/sell1/" + symbol

        form.action = action_src;
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM