0

I did a little googling pset7 index TypeError: 'NoneType' object is not subscriptable error

Found an error similar in my code. But it doesn't say how to fix it. How do I fix the code? Assuming that is what is causing the error.

index

@app.route("/")
@login_required
def index():

    """Show portfolio of stocks"""
    current_id = session["user_id"]

    # count number rows except id
    db_stock_info_num_rows = db.execute("SELECT id FROM stock_info where id = :present_id",
    present_id = current_id)
    # testing rows
    num_rows = db_stock_info_num_rows[0]
    db_rows = num_rows.items()
    rows_len = len(db_rows)
    print("length of rows = {}" , rows_len)

    # count number of columns
    db_stock_info_num_columns = db.execute("SELECT stock_name, stock_symbol ,shares ,stock_price ,stock_total FROM stock_info where id = :present_id",
    present_id = current_id)
    # testing rows
    num_columns = db_stock_info_num_columns[0]
    db_columns = num_columns.items()
    columns_len = len(db_columns)
    print(" length of columns = {}", columns_len)

    # get current symbol from global variable
    current_symbol = session["user_symbol"]

    # select everything but id
    db_stock_info = db.execute("SELECT stock_name, stock_symbol, shares, stock_price, stock_total FROM stock_info WHERE id = :present_id and  stock_symbol = :present_symbol "
    ,present_id = current_id ,present_symbol = current_symbol )

    # get cash_before_purchase from global variable
    cash_before_purchase = session["cash_before_purchase"]
    print("cash_before_purchase {}", cash_before_purchase)

    cash_after_purchase = db.execute('SELECT cash FROM users WHERE id = :present_id and present_symbol',
    present_id = current_id, present_symbol = current_symbol)

    # stock_price * shares
    total_stock_price = db.execute("SELECT stock_total FROM STOCK_INFO WHERE id = :present_id and present_symbol",
    present_id = current_id, present_symbol= current_symbol)

    cash_after_purchase = cash_before_purchase - total_stock_price
    print("cash_after_purchase  {}", cash_after_purchase)

    return render_template("index.html",cash_before_purchase = cash_before_purchase ,db_stock_info = db_stock_info,
    rows_len = rows_len,
    columns_len = columns_len,
    cash_after_purchase=cash_after_purchase)

    return render_template ("index.html")

Buy

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

    if request.method == "POST":

        stock = request.form.get("symbol")
        # get stock information from lookup function
        stocks = lookup(stock.upper())
        user_price = 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/
        # Remove Space at the Start and end of the string in Python  :
        user_symbol = user_symbol.strip()

        current_id = session["user_id"]

        # 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 = :symbol and id = :present_id",
        symbol = request.form.get("symbol"), present_id = current_id)
        print("db_Shares = {}" ,len(db_shares))


        # https://stackoverflow.com/questions/3289601/null-object-in-python
        if len(db_shares) > 0:

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

        # make sure stock name is correct and not blank
        #user_symbol is blank
        if not user_symbol or user_symbol == None:
            return apology("Stock Symbol is inputted incorrect or blank.", 403)

        # user_price * (1 to infinity)
        total_stock_price = user_price * float(not_db_shares)





        cash_before_purchase = db.execute('SELECT cash FROM users WHERE id = :present_id',
        present_id = current_id)
        # global variable
        session["cash_before_purchase"] = cash_before_purchase

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





        # need to add shares
        if len(db_shares) == 0:
        #if not db_shares[0]["shares"]:

            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 = user_symbol,
            total_shares = not_db_shares,
            single_stock_price = user_price,
            total_price = total_stock_price)

        # make global variable
        session["user_symbol"] = request.form.get("symbol")
        return redirect("/")

    else:
        return render_template("buy.html")

index.hmtl

{% extends "layout.html" %}

{% block title %}
    index
{% endblock title %}

{% block main %}




<table>
  <tr>
    <th> SYMBOL </th>
    <th> NAME </th>
    <th> SHARES </th>
    <th> PRICE </th>
    <th> TOTAL </th>
  </tr>

{% for x in range(rows_len) %}
<tr>
  {% for y in range( columns_len) %}
    <td> {{database_stock_info[x][y]}} </td>
  {% endfor %}
</tr>
{% endfor %}
  </tr>
    <th> </th>
    <th> </th>
    <th> </th>
    <th> </th>
    <th> {{ cash_after_purchase[0]["cash"]  }} </th>
  <tr>
      <th> </th>
      <th> </th>
      <th> </th>
      <th> </th>
      <th> {{ cash_before_purchase}} </th>
  </tr>

</table>

{% endblock %}

Error message. It registers but gives internal server error.

 Restarting with stat
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:40:45] "GET / HTTP/1.1" 302 -
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:40:45] "GET /login HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:40:45] "GET /static/styles.css HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:40:46] "GET /favicon.ico HTTP/1.1" 404 -
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:40:48] "GET /register HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:40:48] "GET /static/styles.css HTTP/1.1" 200 -
DEBUG:cs50:select username from users where id >= 1
1
DEBUG:cs50:INSERT INTO users (username, hash) VALUES('wfEDEFE', 'pbkdf2:sha256:50000$BnB1qzuJ$6369803fdf120918208e269f959cd7b677c61db50579460bcb0ec2fd9376e3ca')
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:40:58] "POST /register HTTP/1.1" 302 -
DEBUG:cs50:SELECT id FROM stock_info where id = 174
ERROR:flask.app:Exception on / [GET]
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 67, in index
    num_rows = db_stock_info_num_rows[0]
IndexError: list index out of range
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:40:58] "GET / HTTP/1.1" 500 -
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:40:58] "GET /static/styles.css HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:40:59] "GET /buy HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:41:00] "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" 403 9
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 130, in buy
    user_price = stocks["price"]
TypeError: 'NoneType' object is not subscriptable
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:41:06] "POST /buy HTTP/1.1" 500 -
INFO:werkzeug:127.0.0.1 - - [18/Jun/2019 03:41:06] "GET /static/styles.css HTTP/1.1" 200 -
7
  • The issue is that your call to lookup isn't returning a valid response, so your code can then not deal with stocks. See linked question.
    – curiouskiwi
    Jun 18, 2019 at 4:27
  • How do I fix the code? It tells the problem but not how to fix @curiouskiwi
    – grggthwrth
    Jun 18, 2019 at 4:36
  • Did you sign up for an API key and update your helpers.py so that lookup will work again? (per the answer there)?
    – curiouskiwi
    Jun 18, 2019 at 4:39
  • Here is the code from helpers.py response = requests.get(f"https://api.iextrading.com/1.0/stock/{urllib.parse.quote_plus(symbol)}/quote") Do i go response = requests.get(f"https://api.iextrading.com/1.0/stock/{urllib.parse.quote_plus(aapl)}/quote") ? @curiouskiwi
    – grggthwrth
    Jun 18, 2019 at 5:31
  • 1
    I'd start printing some of the variables that are causing you trouble so you can see exactly what is being returned by your calls to db.execute
    – curiouskiwi
    Jun 19, 2019 at 4:11

0

Browse other questions tagged .