0

Please someone help me to identify what is the root of the problem. I have little time before the new year to submit this task and the final project. The problem is with the check50 of the history of transactions.

:( history page shows transactions Cause expected to find "AAAA" in page, but it wasn't found Log sending GET request to /signin sending POST request to /login sending GET request to /history checking that "28.00" is in page checking that "AAAA" is in page

the code for app is

import os
from datetime import datetime

from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from werkzeug.security import check_password_hash, generate_password_hash

from helpers import apology, login_required, lookup, usd

# Configure application
app = Flask(__name__)

# Custom filter
app.jinja_env.filters["usd"] = usd

# Configure session to use filesystem (instead of signed cookies)
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.after_request
def after_request(response):
    """Ensure responses aren't cached"""
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response


@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    balance = db.execute("SELECT * FROM balance WHERE user_id = ?", session["user_id"])
    stocks_value = 0
    for stock in balance:
        symbol = lookup(stock["symbol"])
        stock["current_stock_price"] = symbol["price"]
        stock["total_stock_value"] = symbol["price"] * stock["quantity"]
        stocks_value += stock["total_stock_value"]
    cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])
    cash = cash[0]["cash"]
    grand_total = stocks_value + cash
    return render_template("index.html", balance=balance, cash=cash, grand_total=grand_total)


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

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure stock name was submitted
        if not request.form.get("symbol"):
                return apology("must provide symbol", 400)

        # Lookup for symbol
        symbol = lookup(request.form.get("symbol"))
        if symbol == None:
            return apology("symbol is not found", 400)

        # Ensure number of shares is correct
        shares = request.form.get("shares")
        try:
            shares = int(shares)
        except:
            return apology("number of shares is incorrect", 400)

        if shares < 0:
            return apology("number of shares must be positive", 400)

        # Query database for usern info
        rows = db.execute("SELECT * FROM users WHERE id = ?", session["user_id"])

        money_to_pay = symbol["price"] * shares
        if money_to_pay > rows[0]["cash"]:
            return apology("not enough money")
        else:
            money_left = rows[0]["cash"] - money_to_pay
            db.execute("UPDATE users SET cash = ? WHERE id = ?", money_left, session["user_id"])
            db.execute("INSERT INTO transactions (user_id, symbol, price, shares, date) VALUES(?, ?, ?, ?, ?)", session["user_id"], symbol["name"], symbol["price"], shares, datetime.utcnow())
            balance_rows = db.execute("SELECT * FROM balance WHERE user_id = ? and symbol = ?", session["user_id"], symbol["symbol"])
            if len(balance_rows) == 0:
                db.execute("INSERT INTO balance (user_id, symbol, quantity) VALUES(?, ?, ?)", session["user_id"], symbol["symbol"], shares)
            elif len(balance_rows) == 1:
                current_quantity = balance_rows[0]["quantity"]
                new_quantity = current_quantity + shares
                db.execute("UPDATE balance SET quantity = ? WHERE user_id = ? and symbol = ?", new_quantity, session["user_id"], symbol["symbol"])


        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("buy.html")


@app.route("/history")
@login_required
def history():
    """Show history of transactions"""
    transactions = db.execute("SELECT * FROM transactions WHERE user_id = ?", session["user_id"])
    return render_template("history.html", transactions=transactions)


@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 = ?", 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("index.html")


@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
    """Get stock quote."""
    # 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("symbol"):
                return apology("must provide symbol", 400)
        symbol = lookup(request.form.get("symbol"))
        if symbol == None:
            return apology("symbol is not found", 400)

        # Lookup for symbol price and render page with it
        symbol = lookup(request.form.get("symbol"))
        return render_template("quoted.html", symbol=symbol)

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("quote.html")


@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""

    # 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", 400)

        # Query database for username
        rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username"))

        # Ensure username does not already exist
        if len(rows) > 0:
            return apology("username already exists", 400)

        # Ensure password was submitted and is the same in both fields
        if not request.form.get("password"):
                return apology("must provide password", 400)

        # Ensure password is the same in both fields
        if request.form.get("password") != request.form.get("confirmation"):
                return apology("password must be the same", 400)

        # If all checks passed write down new user and hashed password into the db
        db.execute("INSERT INTO users (username, hash) VALUES(?, ?)", request.form.get("username"), generate_password_hash(request.form.get("password"), method='pbkdf2', salt_length=16))

        return render_template("register.html")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("register.html")




@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""
    rows = db.execute("SELECT * FROM users WHERE id = ?", session["user_id"])
    balance = db.execute("SELECT * FROM balance WHERE user_id = ?", session["user_id"])
    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        # Ensure stock name was submitted
        if not request.form.get("symbol"):
                return apology("must provide symbol", 400)
        # Lookup for symbol
        symbol = lookup(request.form.get("symbol"))
        if symbol == None:
            return apology("symbol is not found", 400)
        # Ensure stock is owned by the user
        for stock_balance in balance:
            if stock_balance["symbol"] == symbol["symbol"]:
                if stock_balance["quantity"] > 0:
                    break
        else:
            return apology("you do not have the selected stock shares", 400)

        # Ensure number of shares is correct
        shares = request.form.get("shares")
        try:
            shares = int(shares)
        except:
            return apology("number of shares is incorrect", 400)

        if shares < 0:
            return apology("number of shares must be positive", 400)
        # Ensure user has enough shares to sell
        for stock_balance in balance:
            if stock_balance["symbol"] == symbol["symbol"]:
                if stock_balance["quantity"] >= shares:
                    money_to_gain = symbol["price"] * shares
                    money_left = rows[0]["cash"] + money_to_gain
                    db.execute("UPDATE users SET cash = ? WHERE id = ?", money_left, session["user_id"])
                    db.execute("INSERT INTO transactions (user_id, symbol, price, shares, date) VALUES(?, ?, ?, ?, ?)", session["user_id"], symbol["name"], symbol["price"], -shares, datetime.utcnow())
                    current_quantity = stock_balance["quantity"]
                    new_quantity = current_quantity - shares
                    db.execute("UPDATE balance SET quantity = ? WHERE user_id = ? and symbol = ?", new_quantity, session["user_id"], symbol["symbol"])
                    return redirect("/")
        else:
            return apology("you do not have enough shares of the selected stock ", 400)


    # User reached route via GET (as by clicking a link or via redirect)
    else:
        # Query database for usern balance info
        stock_list = [stock["symbol"] for stock in balance]
        return render_template("sell.html", stock_list=stock_list)


@app.route("/change_password", methods=["GET", "POST"])
@login_required
def change_password():
    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure password was submitted
        if not request.form.get("old_password"):
            return apology("must provide password", 400)

        # Query database for username
        rows = db.execute("SELECT * FROM users WHERE id = ?", session["user_id"])

        # Ensure username exists and password is correct
        if not check_password_hash(rows[0]["hash"], request.form.get("old_password")):
            return apology("invalid current password", 400)

        # Ensure new password was submitted
        if not request.form.get("new_password"):
            return apology("must provide new password", 400)

        # Ensure new password matches
        if request.form.get("new_password") != request.form.get("check_password"):
            return apology("passwords do not match", 400)

        db.execute("UPDATE users SET hash = ? where id = ?", generate_password_hash(request.form.get("new_password"), method='pbkdf2', salt_length=16), session["user_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("change_password.html")

the sql statements are

CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT NOT NULL, hash TEXT NOT NULL, cash NUMERIC NOT NULL DEFAULT 10000.00);
CREATE TABLE sqlite_sequence(name,seq);
CREATE UNIQUE INDEX username ON users (username);
CREATE TABLE balance (user_id INTEGER NOT NULL, symbol TEXT NOT NULL, quantity INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (user_id, symbol), FOREIGN KEY (user_id) REFERENCES users (id));
CREATE TABLE transactions (symbol TEXT NOT NULL, shares NUMERIC NOT NULL, price NUMERIC NOT NULL, date TIMESTAMP NOT NULL, user_id INTEGER NOT NULL);

the code for history.html is

{% extends "layout.html" %}

{% block title %}
    History
{% endblock %}

{% block main %}
<table>
    <thead>
        <tr>
            <th>Stock</th>
            <th>Purchase+/sale-</th>
            <th>Purchase/sale price</th>
            <th>Date</th>
        </tr>
    </thead>
    <tbody>
        {% for transaction in transactions %}
            <tr>
                <td class='text-start'>{{transaction.symbol }}</td>
                <td class='text-end'>{{transaction.shares }}</td>
                <td class='text-end'>{{transaction.price | usd }}</td>
                <td class='text-end'>{{transaction.date}}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>
{% endblock %}

Previously I had an autoincrementing id as a primary key of transactions, but removing this column did not help.

1 Answer 1

1

My gut tells me it is from inserting symbol["name"] into transactions instead of symbol["symbol"]

This warning in the spec:

Due to some changes in the distribution code, the company “name” will actually be displayed as its symbol; this is due to a limitation of the API we’ve changed to. Nothing to worry about, but do remember that lookup takes a symbol, so take care not to mix them up in your code!

Suppose check50 sends "aaaa" as the stock symbol? helpers.py converts it to upper, but not so name.

1
  • Thank you so much!
    – Greg
    Commented Dec 21, 2023 at 23:50

You must log in to answer this question.

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