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

    if request.method == "POST":

        symbol = request.form.get("symbol")
        # get stock information from lookup function
        # Remove Space at the Start and end of the string in Python  :
        upper_case_symbol = symbol.upper()
        symbol = upper_case_symbol.strip()
        stocks = lookup(symbol)


        user_price = usd(stocks["price"])
        user_symbol = stocks["symbol"]
        user_fullname = stocks["name"]
        # 1-infinity
        not_db_shares = request.form.get("counter")
        # http://www.datasciencemadesimple.com/remove-spaces-in-python/


        current_id = session["user_id"]
        # make sure stock name is correct and not blank
        if not symbol or symbol == None:
            return apology("Stock symbol is inputted incorrect or blank.", 403)


        # left shares column blank
        # confused by not
        if not request.form.get("counter"):
            return apology("you didn't click shares")

        # put this here because want to count shares before insert
        # may come back empty as in 0 that works
        db_shares = db.execute("SELECT shares FROM stock_info WHERE stock_symbol = :not_db_symbol and id = :present_id",
        not_db_symbol = symbol, present_id = current_id)

        print("db_Shares = {}" ,len(db_shares))

        # if executes add an extra share
        # https://stackoverflow.com/questions/3289601/null-object-in-python



        if len(db_shares) > 0:
            # stock_total
            stock_total = (user_price * int(not_db_shares)) + (db_stock_price[0]["stock_price"] * db_shares[0]["shares"])

            not_db_shares = db_shares[0]["shares"] + int(not_db_shares)
            # update shares
            db.execute("UPDATE stock_info SET shares = :present_shares WHERE id = :present_id and stock_symbol = :not_db_symbol",
            present_shares = not_db_shares ,present_id = current_id, not_db_symbol = symbol)


        else:
            stock_total = user_price * int(not_db_shares)










        db_total_cash = db.execute('SELECT total_cash FROM users WHERE id = :present_id',
        present_id = current_id)



        # can the user afford the stock?
        # if can't return apology
        # cash_before_purchase
        # float(db_total_cash[0]["total_cash"])
        #




        if db_total_cash[0]["total_cash"] < float(stock_total) :
            return apology("You don't have enough money.",403)

        # calculate cash_after purchase
        cash_after_purchase = db_total_cash[0]["total_cash"] - stock_total


        db.execute("UPDATE users SET cash_after_purchase = :update_cash_after_purchase WHERE id = :present_id",
        present_id = current_id, update_cash_after_purchase = cash_after_purchase)

        # add all information in stock_info this is when adding brand new info into a database but may have same id

        if len(db_shares) == 0:


            db_symbol = db.execute("INSERT INTO stock_info (id,stock_name, stock_symbol, shares, stock_price, stock_total)\
            VALUES(:present_id, :name_stock, :user_symbol, :total_shares, :single_stock_price, :total_price)",
            present_id = current_id,
            name_stock = user_fullname,
            user_symbol = symbol,
            total_shares = not_db_shares,
            single_stock_price = user_price,
            total_price = stock_total)




        # pass on stock_symbol to index using global variable
        db_symbol = db.execute("select stock_symbol from stock_info where id = :present_id",
        present_id = current_id)
        print("row 199 {}",len(db_symbol))

        # global variable
        session["user_symbol"] = db_symbol[0]["stock_symbol"]
        session["user_id_2"] = current_id

        return redirect ("/")

    else:
        return render_template("buy.html")

error message below:

 INFO:werkzeug:192.168.151.25 - - [01/Aug/2019 20:36:16] "GET / HTTP/1.0" 302 -
INFO:werkzeug:192.168.151.25 - - [01/Aug/2019 20:36:16] "GET /login HTTP/1.0" 200 -
INFO:werkzeug:192.168.151.25 - - [01/Aug/2019 20:36:16] "GET /static/styles.css HTTP/1.0" 200 -
INFO:werkzeug:192.168.151.25 - - [01/Aug/2019 20:36:18] "GET /register HTTP/1.0" 200 -
INFO:werkzeug:192.168.151.25 - - [01/Aug/2019 20:36:18] "GET /static/styles.css HTTP/1.0" 200 -
DEBUG:cs50:select username from users
username = {} afdafd
DEBUG:cs50:INSERT INTO users (username, hash) VALUES( 'jdfs', 'pbkdf2:sha256:150000$PK61WMsN$36f5ffb190c41efd76a7d1ea76c5068552828420e2983bf11189759fb580ac8a')
INFO:werkzeug:192.168.151.25 - - [01/Aug/2019 20:36:22] "POST /register HTTP/1.0" 302 -
DEBUG:cs50:SELECT total_cash FROM users WHERE id = 83
DEBUG:cs50:SELECT cash_after_purchase FROM users WHERE id = 83
INFO:werkzeug:192.168.151.25 - - [01/Aug/2019 20:36:22] "GET / HTTP/1.0" 200 -
INFO:werkzeug:192.168.151.25 - - [01/Aug/2019 20:36:22] "GET /static/styles.css HTTP/1.0" 200 -
INFO:werkzeug:192.168.151.25 - - [01/Aug/2019 20:36:24] "GET /buy HTTP/1.0" 200 -
INFO:werkzeug:192.168.151.25 - - [01/Aug/2019 20:36:24] "GET /static/styles.css HTTP/1.0" 200 -
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): cloud-sse.iexapis.com:443
DEBUG:urllib3.connectionpool:https://cloud-sse.iexapis.com:443 "GET /stable/stock/AAPL/quote?token=pk_aa72c8cfc63e4abc901ce6b5d26b202e HTTP/1.1" 200 None
DEBUG:cs50:SELECT shares FROM stock_info WHERE stock_symbol = 'AAPL' and id = 83
db_Shares = {} 0
DEBUG:cs50:SELECT total_cash FROM users WHERE id = 83
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/workspace/pset7/finance/helpers.py", line 34, in decorated_function
    return f(*args, **kwargs)
  File "/home/ubuntu/workspace/pset7/finance/application.py", line 202, in buy
    if db_total_cash[0]["total_cash"] < float(stock_total) :
ValueError: could not convert string to float: '$208.43'

second error

INFO:werkzeug:192.168.143.110 - - [02/Aug/2019 18:45:54] "GET / HTTP/1.0" 302 -
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:45:54] "GET /login HTTP/1.0" 200 -
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:45:54] "GET /static/styles.css HTTP/1.0" 200 -
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:45:56] "GET /register HTTP/1.0" 200 -
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:45:56] "GET /static/styles.css HTTP/1.0" 200 -
DEBUG:cs50:select username from users
username = {} afdafd
DEBUG:cs50:INSERT INTO users (username, hash) VALUES( 'erFEFRF', 'pbkdf2:sha256:150000$o64IuVNk$cd13e2176c1157bb08cb8d9947340d69e42c2681b643a9c36ea288654320bae3')
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:46:03] "POST /register HTTP/1.0" 302 -
DEBUG:cs50:SELECT total_cash FROM users WHERE id = 87
DEBUG:cs50:SELECT cash_after_purchase FROM users WHERE id = 87
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:46:03] "GET / HTTP/1.0" 200 -
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:46:03] "GET /static/styles.css HTTP/1.0" 200 -
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:46:06] "GET /buy HTTP/1.0" 200 -
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:46:06] "GET /static/styles.css HTTP/1.0" 200 -
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): cloud-sse.iexapis.com:443
DEBUG:urllib3.connectionpool:https://cloud-sse.iexapis.com:443 "GET /stable/stock/symbol/quote?token=pk_aa72c8cfc63e4abc901ce6b5d26b202e HTTP/1.1" 404 None
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/workspace/pset7/finance/helpers.py", line 34, in decorated_function
    return f(*args, **kwargs)
  File "/home/ubuntu/workspace/pset7/finance/application.py", line 135, in buy
    user_price =  stocks["price"]
TypeError: 'NoneType' object is not subscriptable
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:46:32] "POST /buy HTTP/1.0" 500 -
INFO:werkzeug:192.168.171.40 - - [02/Aug/2019 18:46:32] "GET /static/styles.css HTTP/1.0" 200 -
  • 1
    How do you know it does not convert? Does it crash? If so, is there an error message in the terminal? Might be interesting to also have the table schemas, so we know which types to expect. Please edit relevant info into the question. – Blauelf Aug 1 '19 at 15:16
  • @Blauelf I updated the post and added an error message. – grggthwrth Aug 1 '19 at 20:39
1

The value being coerced has mixed character data (the $ in the case of $208.43). Consider either sanitising the return value or revising the finance.db data type.

| improve this answer | |
  • @Blauelf @Ashen Gunaratne I found the error the was caused by stocks = lookup(symbol). I forgot to do stocks = lookup("symbol"). But a new error appeared TypeError: 'NoneType' object is not subscriptable Normally I just go export API_KEY=value where value is equal to the api key number. Why is this not working? – grggthwrth Aug 2 '19 at 18:55
  • 1
    @grggthwrth I firmly believe it should be lookup(symbol) instead of lookup("symbol") since the life purpose of lookup function is to return a stock quote for a parameterised symbol and by using lookup("symbol") the stock symbol will always remain literally symbol. – Ashen Gunaratne Aug 3 '19 at 4:00
  • What should the finance datatype be in finance.db? Or How do I sanitize the return value ? @Ashen Gunaratne Thanks for the help. – grggthwrth Aug 3 '19 at 5:32
  • Also why does it return none-type error. Are you sure the error is not with the api for yahoo finance? – grggthwrth Aug 4 '19 at 0:40
  • @grggthwrth I believe your are currently storing the the currency symbol in the database (a la $10); a better approach would be to only store the value (a la 10) which shall not only eliminate the casting issue but also remove redundant data from the database. Alternately .lstrip or a similar method can be used to sanitise the return value stripping any leading currency symbols. – Ashen Gunaratne Aug 4 '19 at 7:06

You must log in to answer this question.

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