0

I'd been struggled with this. Here's my code:

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    if request.method == "GET":
        return render_template('buy.html')

    elif request.method == "POST":
        # check if it stock exists
        my_dict = lookup(request.form.get('stock'))
        if my_dict == None:
            return apology("Stock symbol is invalid.")

        num_shares = int(request.form.get('shares'))
        if num_shares < 0:
            return apology("Can't buy a negative number of shares")

        spended = num_shares * my_dict['price']     # (1 * 133.50)

        result = db.execute("SELECT cash from users WHERE id=:id", id= session['user_id'])

        if result[0]['cash'] < spended:  
            return apology("You don't have enough cash")

        # check if the new table 'portafolio' exists

        db.execute("create table if not exists portafolio(id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER,stock TEXT, shares INTEGER, price REAL, date TEXT)");

        # add a log to the table 'portafolio'  %%%% ERROR %%%%
        db.execute("INSERT INTO portafolio(user_id, stock, shares, price, date) VALUES( session['user_id'], my_dict['symbol'], shares, my_dict['price'], CURRENT_DATE)");  

        # update cash from 'users' table            
        db.execute("UPDATE users SET cash=cash-spended where id=:id", id= sesion['user_id']) 

        return redirect(url_for('index'))

Whenever I ran my website it points to this as a problem. Apparently the way I'm using my_dictto access the symbol andprice is wrong.

Here's the error:

builtins.RuntimeError
RuntimeError: (sqlite3.OperationalError) near "['symbol']": syntax error [SQL: "INSERT INTO portafolio(user_id, stock, shares, price, date) VALUES( session['user_id'] , my_dict['symbol'], shares, my_dict['price'], CURRENT_DATE)"]

Any help would be greatly appreciated guys.

  • In the line where error happened, VALUES (...shares...) should be VALUES (...num_shares...)??? – glenyu80119 Jan 18 '17 at 1:19
  • Yeah I know where, I don't know how to fix that. – tadm123 Jan 18 '17 at 2:33
  • 1
    In the parenthesis next to VALUES you should use named bind parameters, e.g. (INSERT INTO ..........VALUES ( :user_id, :symbol,.....), user_id = session['user_id'], symbol = ........) – glenyu80119 Jan 18 '17 at 7:14
  • Oh yeah, very silly mistake that I overlooked. Thanks! – tadm123 Jan 18 '17 at 8:04
  • 1
    No problem! I'm also working on this pset. It's quite confusing i think. Good luck! – glenyu80119 Jan 18 '17 at 8:20

You must log in to answer this question.

Browse other questions tagged .