0

Here is my code so far for "/buy"

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""

    # User reached route via GET (as by clicking a link or via redirect)
    if request.method == "GET":
        return render_template("/buy.html")

    # User reached route via POST
    else:
        #get quote using lookup function
        symbol_input = request.form.get("symbol")
        quote = lookup(symbol_input)
        shares = (request.form.get("shares"))
        name = quote["name"]
        price = quote["price"]
        symbol = quote["symbol"]
        id = session["user_id"]


        # check if symbol returns anything from lookup (does the symbol exist?)
        if not quote:
            return apology("Invalid symbol")
        else:
            # gets cash balance for user
            user_balance = db.execute("SELECT cash FROM users WHERE id = :id", id=id)
            user_balance = user_balance[0]["cash"] # changes variable from a list of dicts to the actual value in table which is a float

            # check that the shares input was both an integer and greater than zero
            # using try/except method used from here https://stackoverflow.com/questions/47321862/how-to-validate-number-is-greater-than-0-in-python
            try:
                shares_int = int(request.form.get("shares")) #tries to cast user input to an int
            except ValueError: # if user didn't enter a number then unable to cast from string to an int
                shares_int = None

            if shares_int is None:
                return apology('Please enter a valid number')

            elif shares_int <= 0:
                return apology('Number should be greater than 0')
            else:
                pass

                transaction_amount = (shares_int * price)
                if user_balance >= transaction_amount: # checks user can afford
                    user_balance = user_balance - transaction_amount # deducts amount from variable and plugs that into UPDATE statement as new value for cash
                    # update_user_balance = db.execute("UPDATE users SET cash = :cash, WHERE id = :id", cash=user_balance, id=id)
                    db.execute("UPDATE users SET cash = :cash, WHERE id = :id", cash=user_balance, id=id)
                    db.execute("INSERT INTO transactions (symbol, name, shares, price, id, transaction_amount) VALUES(:symbol, :name, :shares_int, :price, :id, :transaction_amount);", symbol=symbol, name=name, shares_int=shares_int, price=price, id=id, transaction_amount=transaction_amount)
                    # update_transactions = db.execute("INSERT INTO transactions (symbol, name, shares, price, id, transaction_amount) VALUES(:symbol, :name, :shares_int, :price, :id, :transaction_amount);", symbol=symbol, name=name, shares_int=shares_int, price=price, id=id, transaction_amount=transaction_amount)
                    # Redirect user to home page
                    return redirect("/")
                else:
                    return apology('You have insufficient funds')

After submitting the number of Shares and Symbol in my html page here:

{% extends "layout.html" %}

{% block title %}
    Buy
{% endblock %}

{% block main %}
    <form action="/buy" method="post">
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="symbol" placeholder="Symbol" type="text">
        </div>
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="shares" placeholder="Shares" type="text">
        </div>

        <button class="btn btn-primary" type="submit">Buy</button>
    </form>
{% endblock %}

I get the following errors in console:

DEBUG:cs50:SELECT cash FROM users WHERE id = 3
DEBUG:cs50:UPDATE users SET cash = 9744.18, WHERE id = 3
ERROR:application:Exception on /buy [POST]
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/ubuntu/environment/pset8/finance/helpers.py", line 34, in decorated_function
    return f(*args, **kwargs)
  File "/home/ubuntu/environment/pset8/finance/application.py", line 107, in buy
    db.execute("UPDATE users SET cash = :cash, WHERE id = :id", cash=user_balance, id=id)
  File "/usr/local/lib/python3.7/site-packages/cs50/flask.py", line 39, in _execute_after
    return _execute_before(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 286, in execute
    raise e
RuntimeError: (sqlite3.OperationalError) near "WHERE": syntax error
[SQL: UPDATE users SET cash = 9744.18, WHERE id = 3]
(Background on this error at: http://sqlalche.me/e/e3q8)
INFO:werkzeug:192.168.91.25 - - [03/Nov/2019 10:31:23] "POST /buy HTTP/1.0" 500 -
INFO:werkzeug:192.168.91.25 - - [03/Nov/2019 10:31:23] "GET /static/styles.css HTTP/1.0" 200 -
INFO:werkzeug: * Detected change in '/home/ubuntu/environment/pset8/finance/application.py', reloading

So as far as I can make out it is failing to update my users table.

DEBUG:cs50:UPDATE users SET cash = 9744.18, WHERE id = 3

I've at visited the link provided here:

RuntimeError: (sqlite3.OperationalError) near "WHERE": syntax error
[SQL: UPDATE users SET cash = 9744.18, WHERE id = 3]
(Background on this error at: http://sqlalche.me/e/e3q8)

Which says operational error is something to do with db connection but I highly suspect I've done something wrong

Any hints would be massively appreciated as I'm starting to feel out of my depth!

1

I would delete the comma near where:

"UPDATE users SET cash = :cash  WHERE id = :id"
2
  • Thank you! (rest assured I feel very stupid asking this now)
    – James
    Nov 3 '19 at 22:01
  • You shouldn't feel bad about it, syntax errors are common, even after years of experience. Luckily they are usually easy to detect
    – MARS
    Nov 3 '19 at 23:05

You must log in to answer this question.

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