I have a lot of work from finance 2017, but it seems to use a different API than what I used last year. How do I update my code to use this new API? Or can I just use the one from last year? (I don't remember where/what that API was) So here's my previous code, help with how to update it to work with this API (Hopefully easily to do) would be great, Thanks!
import os
from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions
from werkzeug.security import check_password_hash, generate_password_hash
from helpers import apology, login_required, lookup, usd
# Ensure environment variable is set
if not os.environ.get("API_KEY"):
raise RuntimeError("API_KEY not set")
# Configure application
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# Custom filter
app.jinja_env.filters["usd"] = usd
# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")
@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""
# Once a user makes a purchase they will be redirected to their index page
# Edit that to reflect the user's portfolio
# Get symbol, shares, cash from databases
purchases = db.execute("SELECT stock, SUM(shares) as sumshares FROM transactions WHERE user_id = :user_id GROUP BY stock ORDER BY stock ASC", user_id = session["user_id"])
usercash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])
usercash = int(usercash[0]["cash"])
# Declare variable for running total of stock value
totalvalstock = 0
# PDHTEFW7T4KOTDHI
# Purchases query will return dicts, loop to iterate over list of dicts.
for purchase in purchases:
purchase['stock'] = purchase["stock"]
shares = purchase['sumshares']
purchase['symbol'] = purchase['stock']
currentstock = lookup(purchase['stock'])
purchase['price'] = currentstock['price']
purchase['singlestocktotal'] = purchase['sumshares'] * purchase['price']
purchase["totalvalstock"] = round(purchase['singlestocktotal'],2)
totalvalstock += purchase['totalvalstock']
# calculate total of all stock holdings at their current price and whatever cash the user has left.
grandtotalstocks = round(totalvalstock,2)
overalltotal = round(grandtotalstocks + usercash,2)
# call render_template and pass variables to html template
return render_template("index.html", purchases=purchases, usercash=usercash, grandtotalstocks=grandtotalstocks,overalltotal=overalltotal,)
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
if request.method == "POST":
shares = float(request.form.get("shares"))
newshares = float(request.form.get("shares"))
stock = lookup(request.form.get("symbol"))
if not stock:
return apology("Invalid Symbol")
elif not shares:
return apology("shares must be more than 0")
price = stock['price']
if shares <= 0:
return apology("shares must be > 0")
cash_balance = db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"])
total_cost = shares * price
if total_cost <= cash_balance[0]["cash"]:
user_id = session["user_id"]
cash_remaining = cash_balance[0]["cash"] - total_cost
#db.execute("INSERT INTO transactions (user_id, stock, price, num_shares, total_cost) \
#VALUES (:user_id, :stock, :price, :num_shares, :total_cost)",
#user_id=session["user_id"], stock=stock, price=price, num_shares=num_shares, total_cost=total_cost)
#PDHTEFW7T4KOTDHI
db.execute("INSERT INTO transactions (user_id, stock, price, shares, total_cost) \
VALUES (:user_id, :stock, :price, :shares, :total_cost)",
user_id=session["user_id"], stock=stock["symbol"], price=price, shares=shares, total_cost=total_cost),
db.execute("UPDATE users SET cash=:new_cash WHERE id=:user_id;", new_cash=cash_remaining, user_id=user_id)
#db.execute("INSERT INTO portfolio (user_id, stock, shares) VALUES (:user_id, :stock, :shares) \
#ON DUPLICATE KEY UPDATE portfolio set shares = shares + :newshares WHERE user_id = user_id AND stock = stock", \
#user_id=session["user_id"], stock=stock["symbol"], shares = shares, newshares = newshares)
db.execute("INSERT INTO portfolio (user_id, stock, shares) VALUES (:user_id, :stock, :shares) \
ON DUPLICATE KEY UPDATE shares = shares + :newshares", user_id=session["user_id"], stock=stock["symbol"], shares = shares, newshares = newshares)
db.execute("UPDATE portfolio SET shares = shares + :newshares WHERE user_id = user_id AND stock = stock\
", user_id=session["user_id"], stock=stock["symbol"], shares = shares, newshares = newshares)
#"INSERT INTO portfolio (user_id, stock, shares) VALUES (:user_id, :stock, :shares)", user_id=session["user_id"], stock=stock["symbol"], shares=shares)
#return apology("good")
#return apology("Looks good")
return render_template("buy.html")
else:
return apology("You can't afford that many shares")
else:
return render_template("buy.html")
@app.route("/history")
@login_required
def history():
"""Show history of transactions"""
return apology("TODO")
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username", 403)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("must provide password", 403)
# Query database for username
rows = db.execute("SELECT * FROM users WHERE username = :username",
username=request.form.get("username"))
# Ensure username exists and password is correct
if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
return apology("invalid username and/or password", 403)
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/")
@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
"""Get stock quote."""
if request.method == "GET":
return render_template("quote.html")
else:
symbol = request.form.get("symbol")
results= lookup(symbol)
if not results:
return apology("invalid stock symbol")
else:
return render_template("quoted.html", quoted = results)
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user."""
session.clear()
if request.method == "POST": #POST CONDITIONAL
#eturn render_template("register.html") # TRIED RETURNING TEMPLATE AT START
if not request.form.get("username"):
return apology("must provide username")
elif not request.form.get("password"):
return apology("must provide password")
elif not request.form.get("confirmation"):
return apology("must confirm password")
elif not request.form.get("password") == request.form.get("confirmation"):
return apology("password must match password confirmation")
hash = generate_password_hash(request.form.get("password"))
result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=hash)
if not result:
return apology("username is already taken")
session["user_id"] = result
#session["user_id"] = result[0]["id"]
return render_template("index.html")
else:
return render_template("register.html")
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
"""Sell shares of stock"""
#return apology("TODO")
# PDHTEFW7T4KOTDHI
if request.method == "POST":
shares = int(request.form.get("shares"))
stock = lookup(request.form.get("symbol"))
#stockprice = stock['price']
if not stock:
return apology("Invalid Symbol")
if shares <= 0:
return apology("shares must be > 0")
amount = int(shares) * stock["price"]
db.execute("UPDATE users SET cash = cash + :amount WHERE id = :userID", amount=amount, userID=session["user_id"])
db.execute("INSERT INTO transactions (user_id, stock, shares, amount, price) VALUES (:user_id, :stock, :shares, :amount, :price)", user_id=session["user_id"], stock = stock["symbol"], shares = shares, amount = amount, price = stock["price"])
db.execute("UPDATE transactions SET shares = shares - :shares WHERE user_id = :user_id AND stock = :stock", shares = shares, user_id=session["user_id"], stock = stock["symbol"])
return apology("good")
else:
return render_template("sell.html")
def errorhandler(e):
"""Handle error"""
return apology(e.name, e.code)
# listen for errors
for code in default_exceptions:
app.errorhandler(code)(errorhandler)