I am doing Finance and I am fighting with this code... could anyone help me? I want to "select" some data from a sql table and put this value to a variable in python (a specific FLOAT number) to use later but, it's give me an internal error. Maybe because SQL return a dict instead a float number. How could I solve it? or maybe it'd be better to ask: How could I take the value inside the dict that "SELECT" give me.

Here is my code:

@app.route("/buy", methods=["GET", "POST"])
def buy():
    """Buy stock quote."""
    """change the data of html POST to python"""
    if request.method == "POST":
        symbol = request.form.get("symbol")
        stock = int(request.form.get("numberofshares"))
        usuario_actual = session["user_id"]
        """give the time"""
        now = datetime.now()

        """look of info about the symbol they gave me""
        share = lookup(symbol)

        """I take the total price of the buy"""
        total_price = share['price'] * stock

        """money in pocket ¡¡¡HERE IS THE PROBLEM!!!"""
        dict_gastos = db.execute("SELECT sum(total) FROM transacciones WHERE user_id = :id", id=usuario_actual)
        dict_cash = db.execute("SELECT cash FROM users WHERE id = :id", id=usuario_actual)
        gastos = float(dict_gastos.values)
        cash = float(dict_cash.values)

        """crear la transacción"""
        monto_acciones = float(share["price"]) * stock
        if share != None:
            if gastos <= cash:
                db.execute("INSERT INTO transacciones (user_id, symbol, cuantas, total, fecha) VALUES (:user_id, :symbol, :cuantas, :total, :fecha)", user_id=session["user_id"], symbol=symbol, cuantas=stock, total=monto_acciones, fecha=now)
                return render_template("buy2.html")
                return apology("You don't have enough money, please try again", 408)
            return apology("This symbol doesn't exist, please try again", 409)
        return render_template("buy.html")

Thank you very much!


From the CS50 Library for Python doc for execute


for SELECTs, a list of dict objects, each of which represents a row in the result set; for INSERTs, the primary key of a newly inserted row (or None if none); for UPDATEs, the number of rows updated; for DELETEs, the number of rows deleted; for CREATEs, True on success; on error, a RuntimeError is raised

dict_gastos is a list with one element, which is a dict with one key/value pair.

This dict_gastos[0]['sum(total)'] will give the number returned from the sql.

One hint: column names in a SELECT can be aliased, given a different name, like so:

SELECT sum(total) as total from....... It would just be typing convenience, because then the key in the returned dict will be total instead of sum(total).

Remember: in the flask run terminal there is a traceback with gives more details information on the error received.

  • thank you very much my friend!!! This was very helpful to me! I can follow with the code now! no more obstacles, "for now" jajaj – santiago correa Jul 27 '20 at 0:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .