提问人:AA-SLF 提问时间:11/4/2023 更新时间:11/5/2023 访问量:35
check50 出错,而我在实际使用它时没有出错
error with check50 while i got no error when i actully use it
问:
我试图提交我的财务代码以完成我在哈佛课程的第 9 周,但由于某种原因,check50 在登录时出现错误,而我一无所获,错误:(以注册用户身份登录成功 原因应用程序引发异常,这是我的代码
import os
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 datetime import datetime
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"""
list = db.execute("SELECT stocks FROM stock WHERE username =(SELECT username FROM loged_in)")
stocks = int(list[0]['stocks'])
result = lookup('NFLX')
price = int(result['price'])
total = price * stocks
""" , stocks, price, total """
return render_template("indix.html", stocks=stocks, price=price, total=total)
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
if request.method == "POST":
list = db.execute("SELECT username FROM loged_in")
name = list[0]['username']
stock = request.form.get("stock_name")
result = lookup(stock)
shares = int(request.form.get("shares"))
price = int(result['price']*shares)
list2 = db.execute("SELECT cash FROM users WHERE username = ?", name)
wallet = int(list2[0]['cash'])
if not result:
return apology("sorry this symbol doesnt exist")
elif shares < 1:
return apology("please enter a positive number")
elif price < wallet:
wallet -= price
list3 = db.execute("SELECT stocks FROM stock WHERE username = ?", name)
stocks = int(list3[0]['stocks'])
newstocks = stocks + shares
""" return render_template("test.html", name = newstocks) """
db.execute("UPDATE users SET cash = ? WHERE username = ?", wallet ,name)
db.execute("UPDATE stock SET stocks = ? WHERE username = ?", newstocks ,name)
else:
return apology("sorry you dont have enough money")
done = (f"you bought {shares} shares from NFLX")
time = datetime.now()
now = (f"{time.year}/{time.month}/{time.day} Time={time.hour}:{time.minute}")
db.execute("INSERT INTO history (username, done, time) VALUES(?, ?, ?)", name, done, now)
return render_template("thank.html")
else:
return render_template("buying.html")
@app.route("/history")
@login_required
def history():
"""Show history of transactions"""
list = db.execute("SELECT username FROM loged_in")
name = list[0]['username']
list2 = db.execute("SELECT done FROM history WHERE username = ?", name)
list3 = db.execute("SELECT time FROM history WHERE username = ?", name)
times = []
names = []
i = 0
for n in list2:
names.append(list2[i]['done'])
times.append(list3[i]['time'])
i += 1
number = len(names)
return render_template("history.html", name = names, number = number, time = times)
@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":
#DELETE the last log in
db.execute("DELETE FROM loged_in")
# 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
name = request.form.get("username")
session["user_id"] = rows[0]["id"]
db.execute("INSERT INTO loged_in (username) VALUES(?)", name)
# 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 == "POST":
qoute = request.form.get("quote-name")
final = lookup(qoute)
if final:
return render_template("quoted.html", final=final)
else:
return apology("sorry this symbol doesnt exist")
else:
return render_template("quote.html")
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
name = request.form.get("username")
password = request.form.get("password")
confirm = request.form.get("confirmation")
if not password or not name or not confirm:
return apology("please fill all the empty placeholders")
if password != confirm:
return apology("your passowrd is not the same")
list = db.execute("SELECT username FROM users;")
username = []
i = 0
for n in range(len(list)):
username.append(list[i]['username'])
i += 1
for names in username:
if names == name:
return apology("sorry this name already exist")
hash_password = generate_password_hash(password)
db.execute("INSERT INTO users (username, hash) VALUES(?, ?)", name, hash_password)
db.execute("INSERT INTO stock (username, stocks) VALUES(?, 0)", name)
return render_template("login.html")
else:
return render_template("register.html")
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
"""Sell shares of stock"""
if request.method == "POST":
list = db.execute("SELECT username FROM loged_in")
name = list[0]['username']
stock = request.form.get("stock_name_sell")
result = lookup(stock)
shares = int(request.form.get("shares_sell"))
price = int(result['price']*shares)
list2 = db.execute("SELECT cash FROM users WHERE username = ?", name)
wallet = int(list2[0]['cash'])
time = datetime.now()
now = (f"{time.year }/{time.month}/{time.day} Time={time.hour}:{time.minute}")
if not result:
return apology("sorry this symbol doesnt exist")
elif shares < 1:
return apology("please enter a positive number")
else:
list3 = db.execute("SELECT stocks FROM stock WHERE username = ?", name)
stocks = int(list3[0]['stocks'])
if stocks >= shares:
newstocks = stocks - shares
else:
return apology("you dont have enough shares to sell")
wallet += price
db.execute("UPDATE users SET cash = ? WHERE username = ?", wallet ,name)
db.execute("UPDATE stock SET stocks = ? WHERE username = ?", newstocks ,name)
done = (f"you sold {shares} shares from NFLX")
db.execute("INSERT INTO history (username, done, time) VALUES(?, ?, ?)", name, done, now)
return render_template("thank.html")
else:
return render_template("sell.html")
Sry for the Long Code,但我只是注意到问题可能不在于登录,因为哈佛已经给了我该代码,我只是添加了 SQL 代码
答:
0赞
DinoCoderSaurus
11/5/2023
#1
问题似乎出在 . 最终重定向到 ;新注册用户没有持有股票。不会返回任何行,因此此行将产生错误。请注意,对查找进行硬编码也可能会对检查器产生错误。要模拟功能,请注册一个新用户并登录。IMO 它正在要求修改提供的登录名的麻烦(并且没有必要)。index
register
index
SELECT
stocks = int(list[0]['stocks'])
NFLX
check50
评论