0

I have been struggling with the buy portion of the finance assignment for CS50. I have created my new tables and written down the logic concerning buying stocks. When I run flask and try to purchase stocks I get a run time error saying that the name, price and symbol of the stocks are 'unsupported values.'

Attached my code. Could someone point me in the right direction?

Thanks!

Rutger

  1. buy.html {% extends "layout.html" %}

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

{% block main %} <button id="submit class="btn btn-primary" type="submit">Submit

{% endblock %}

  1. buy in application.py @app.route("/buy", methods=["GET", "POST"]) @login_required def buy():

    #requires creation of two tables in db. #1)table that stores transaction details #2) table that stores stocks beloning to user

    """Buy shares of stock""" if request.method =="POST":

     # store lookup; quantity and price in variable
     stock_lookup = lookup(request.form.get("symbol"))
     quantity = int(request.form.get("quantity"))
     stock_price = stock_lookup["price"]
     user_id = session["user_id"]
    
    
     # check for correct symbol
     if not stock_lookup:
         return apology("Unable to find stock", 403)
    
     # make sure user inputs at least 1 share
     elif quantity <1:
         return apology("Must be positive number", 403)
    
     #company in db?
     company_exist = db.execute("SELECT company_id FROM company_overview WHERE company_symbol = :symbol", symbol=stock_lookup)
     #if company not present in db, insert into db
     if len(company_exist)== 0:
         company_id = db.execute("INSERT INTO 'company_overview' ('company_name', 'company_symbol) VALUES (:name, :symbol)", name = stock_lookup["name"], symbol=stock_lookup["symbol"])
    
     else:
         company_id = company_exist[0]["company_id"]
    
    
     #check if wallet can accomodate transaction
     wallet = db.execute("SELECT cash FROM users WHERE id=:user_id", user_id=session["user_id"])[0]["cash"]
    
     #price calculation
     value = stock_price * quantity
    
    
     #display error message if value exceeds wallet
     if value > wallet:
         return apology("You do not have sufficient funds", 403)
    
     #value of wallet after purchasing stock
     wallet = wallet - value
    
     #append transaction to cash balance in user db
     db.execute("UPDATE users SET cash=:cash WHERE user_id=:user_id", cash=wallet, user_id=user_id)
    
     #append transaction to transaction_overview
     db.execute("""INSERT INTO 'transaction_overview' ('user_id', 'company_id', 'quantity', 'stock_price', 'timestamp')
     VALUES (:user_id, :company_id, :quantity, :stock_price, datetime('now'))""",
     user_id=user_id, company_id = company_id, quantity=quantity, stock_price=stock_price)
    
     #return bought message for user
     flash("Purchased")
    
     return redirect("/")
    

    else: return render_template("buy.html")

  2. The error I am getting ERROR:application:Exception on /buy [POST] Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1821, 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 1950, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functionsrule.endpoint File "/home/ubuntu/pset8/finance/helpers.py", line 34, in decorated_function return f(*args, **kwargs) File "/home/ubuntu/pset8/finance/application.py", line 76, in buy company_exist = db.execute("SELECT company_id FROM company_overview WHERE company_symbol = :symbol", symbol=stock_lookup) File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 21, in decorator return f(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 220, in execute tokens[index] = self._escape(kwargs[name]) File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 460, in _escape return __escape(value) File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 454, in __escape raise RuntimeError("unsupported value: {}".format(value))

RuntimeError: unsupported value: {'name': 'Apple, Inc.', 'price': 118.64, 'symbol': 'AAPL'} INFO:werkzeug:192.168.171.20 - - [20/Nov/2020 09:18:17] "POST /buy HTTP/1.0" 500 - INFO:werkzeug:192.168.171.20 - - [20/Nov/2020 09:18:18] "GET /static/styles.css HTTP/1.0" 200 -

0

Look at the difference between the parameters passed to execute here

company_id = db.execute("INSERT INTO 'company_overview' ('company_name', 'company_symbol) 
VALUES (:name, :symbol)", name = stock_lookup["name"], symbol=stock_lookup["symbol"])

and here

 company_exist = db.execute("SELECT company_id FROM company_overview WHERE company_symbol = :symbol",
 symbol=stock_lookup)

stock_lookup is a dictionary, the return value of lookup. Since the error is being provoked in the CS50 sql library, it makes it harder to unravel what is going on.

1
  • Thank you! This seems to solve the issue. – rutgerv Nov 20 '20 at 14:00
0

I now run into the following issue:

DEBUG:cs50:SELECT company_id FROM company_overview WHERE company_symbol = 'AAPL' DEBUG:cs50:SELECT cash FROM users WHERE id=8 DEBUG:cs50:UPDATE users SET cash=9050.88 WHERE id=8 DEBUG:cs50:INSERT INTO transaction_overview (transaction, user_id, company_id, quantity, stock_price, timestamp) VALUES ('buy', 8, 2, 1, 118.64, datetime('now')) ERROR:application:Exception on /buy [POST] Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1821, 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 1950, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functionsrule.endpoint File "/home/ubuntu/pset8/finance/helpers.py", line 34, in decorated_function return f(*args, **kwargs) File "/home/ubuntu/pset8/finance/application.py", line 106, in buy transaction_type='buy', user_id=user_id, company_id = company_id, quantity=quantity, stock_price=stock_price) File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 21, in decorator return f(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 372, in execute raise e

RuntimeError: near "transaction": syntax error

The error is referring to the following section: #append transaction to transaction_overview db.execute("""INSERT INTO transaction_overview (transaction, user_id, company_id, quantity, stock_price, timestamp) VALUES (:transaction_type, :user_id, :company_id, :quantity, :stock_price, datetime('now'))""", transaction_type='buy', user_id=user_id, company_id = company_id, quantity=quantity, stock_price=stock_price)

I created the transaction_overview table with: CREATE TABLE "transaction_overview" ('transaction_id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'transaction' TEXT, 'user_id' INTEGER NOT NULL, 'company_id' INTEGER NOT NULL, 'quantity' INTEGER NOT NULL, 'stock_price' INTEGER NOT NULL, 'timestamp' DATETIME NOT NULL);

Would you know what I am doing wrong here?

1

You must log in to answer this question.

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