Buy function

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

    if request.method == "POST":

        stock = request.form.get("symbol").upper()
        stocks = lookup(request.form.get("symbol").upper())

        # get every item of the list
        # id stock_symbol stock_name stock_price
        stock_price = stocks["price"]
        stock_symbol = stocks["symbol"]
        stock_fullname = stocks["name"]
        # 1-infinity
        shares = request.form.get("counter")
        # stock_price * 1 to infinity
        total_stock_price = stock_price * float(shares)

        # http://www.datasciencemadesimple.com/remove-spaces-in-python/
        # Remove Space at the Start and end of the string in Python  :
        stock_symbol = stock_symbol.strip()

        current_id = session["user_id"]

        """db.execute("INSERT INTO stock_info (id,stock_symbol, stock_name, stock_price, stock_total)


        # prety sure don't need this line stock_symbol_db = db.execute("SELECT stock_symbol FROM stock_info where id = current_id")

        # make sure stock name is correct and not blank
        # if symbol does not matches list of stocks
        # ex AAPL == AAPL comes back true
        # make sure stock symbol inputed
        if not stock_symbol:
            return apology("Stock Symbol is inputted incorrect or blank.", 403)

        current_cash = db.execute("SELECT cash FROM users where id = current_id")

        # can the user afford the stock?
        # if can't return apology
        if current_cash[0]["cash"] < total_stock_price:
            return apology("You don't have enough money.",403)

        # double check
        cash_after_purchase = current_cash[0]["cash"] - total_stock_price
        db.execute("INSERT INTO users (cash) VALUES('cash_after_purchase=cash_after_purchase')")

        database_stock_info = db.execute("select * from stock_info where id = current_id")

        # https://www.w3schools.com/sql/sql_count_avg_sum.asp
        # count number rows

        db_stock_info_num_rows = db.execute("SELECT COUNT (id) FROM stock_info where id = current_id")

        # https://stackoverflow.com/questions/658395/find-the-number-of-columns-in-a-table
        # count number of columns

        db_stock_info_num_col = """
        db.execute("SELECT COUNT (*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo'AND stock_info = stock_info")

        return render_template("successfully_bought.html",current_cash = current_cash ,database_stock_info = database_stock_info,
        db_stock_info_num_rows = db_stock_info_num_rows, db_stock_info_num_col = db_stock_info_num_col,

        #return render_template("successfully_bought.html", stock_symbol=stock_symbol, stock_fullname=stock_fullname,
        #stock_price=stock_price, cash_after_purchase=cash_after_purchase, current_cash=current_cash, shares=shares)

        return render_template("buy.html")

Here is my error I am getting. The error is coming from

 'SELECT cash FROM users where id = current_id'

I always thought session["user_id"]should carry over to a different function. Why does it not? I didn't make id a primary key or auto increment in the database stock_info. I made cash in the database users a default value of 10000 # add username and hash password even add current username

Here is the code from register for session["user_id"]

id_db = db.execute("INSERT INTO users (username, hash) VALUES(:username_input, :hashed_pwd)",
        username_input = request.form.get("username"), hashed_pwd=secure_password)

    # Remember which user has logged in
    session["user_id"] = id_db

database called users


1   bob    rhr   10000

# None of the names are capitalized in the code I mistype don't want to retype.

database called stock_info


1   AAPL   apple     1      555     455
1   GOOG   google    1      355.    100

End of databases

Restarting with stat
INFO:werkzeug: - - [24/May/2019 04:20:47] "GET / HTTP/1.1" 302 -
INFO:werkzeug: - - [24/May/2019 04:20:47] "GET /login HTTP/1.1" 200 -
INFO:werkzeug: - - [24/May/2019 04:20:47] "GET /static/styles.css HTTP/1.1" 200 -
INFO:werkzeug: - - [24/May/2019 04:20:49] "GET /register HTTP/1.1" 200 -
INFO:werkzeug: - - [24/May/2019 04:20:49] "GET /static/styles.css HTTP/1.1" 200 -
DEBUG:cs50:INSERT INTO users (username, hash) VALUES('qreg', 'pbkdf2:sha256:50000$wi5JzzO1$810aa6f4dbf58dd6a20f249c2f410984f48919b233ecd15a1bc30a76e06a3310')
INFO:werkzeug: - - [24/May/2019 04:20:55] "POST /register HTTP/1.1" 302 -
INFO:werkzeug: - - [24/May/2019 04:20:55] "GET / HTTP/1.1" 400 -
INFO:werkzeug: - - [24/May/2019 04:20:56] "GET /static/styles.css HTTP/1.1" 200 -
INFO:werkzeug: - - [24/May/2019 04:20:57] "GET /buy HTTP/1.1" 200 -
INFO:werkzeug: - - [24/May/2019 04:20:57] "GET /static/styles.css HTTP/1.1" 200 -
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.iextrading.com
DEBUG:urllib3.connectionpool:https://api.iextrading.com:443 "GET /1.0/stock/AAPL/quote HTTP/1.1" 200 None
DEBUG:cs50:SELECT cash FROM users where id = current_id
ERROR:flask.app:Exception on /buy [POST]
Traceback (most recent call last):
  File "/opt/pyenv/versions/3.6.0/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/opt/pyenv/versions/3.6.0/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/opt/pyenv/versions/3.6.0/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/opt/pyenv/versions/3.6.0/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/opt/pyenv/versions/3.6.0/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/opt/pyenv/versions/3.6.0/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/ubuntu/workspace/pset7/finance/helpers.py", line 39, in decorated_function
    return f(*args, **kwargs)
  File "/home/ubuntu/workspace/pset7/finance/application.py", line 117, in buy
    current_cash = db.execute("SELECT cash FROM users where id = current_id")
  File "/opt/pyenv/versions/3.6.0/lib/python3.6/site-packages/cs50/sql.py", line 224, in execute
    raise e
RuntimeError: no such column: current_id [SQL: 'SELECT cash FROM users where id = current_id']
INFO:werkzeug: - - [24/May/2019 04:21:03] "POST /buy HTTP/1.1" 500 -
INFO:werkzeug: - - [24/May/2019 04:21:04] "GET /static/styles.css HTTP/1.1" 200 -

'SELECT cash FROM users where id = current_id' expects the database to know current_id, but it is a Python variable, so the database has no idea. You should use a template there, and a named parameter, like

db.execute('SELECT cash FROM users WHERE id = :user_id', user_id=current_id)

(I chose a different name for the named parameter just to show which parts should match)

Your code has more issues. For example, the form parameter needs to be shares as required by the problem specification, not counter, or the tests will fail.

If symbol is empty or does not represent a valid symbol, lookup will return None. NoneType is not subscriptible, meaning stocks["price"] will be an insta-crash if stocks is None.

You should probably use UPDATE, not INSERT to change the value of cash.

More issues, you'll run into them when fixing the others, but that would be enough for another question or two.

You must log in to answer this question.

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