0

I have implemented all functions. However when i run check50, it gets following errorsenter image description here

The errors might come from my index code. I am not sure. Below are my code for register and index. Any suggestion would be much appreciated.

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

    # Ensure username was submitted
    if not request.form.get("username"):
        return apology("must provide username")

    # Ensure password was submitted
    elif not request.form.get("password"):
        return apology("must provide password")

    elif not request.form.get("confirmation"):
        return apology("must confirm your password")

    elif request.form.get("password") != request.form.get("confirmation"):
        return apology("password don't match")

    # Add username and password to database
    result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=generate_password_hash(request.form.get("password")))
    if not result:
        return apology("username already in use")

    rows = db.execute("SELECT * FROM users WHERE username = :username",
                      username=request.form.get("username"))

    session["user_id"] = rows[0]["id"]

    return redirect("/")

else:
    return render_template("register.html")

Index:

@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""
   rows_pt = db.execute("SELECT * FROM portfolio WHERE id = :id",id = session["user_id"])

if rows_pt == []:
    cash_b = db.execute("SELECT cash FROM users WHERE id = :id",id = session["user_id"])
    cash = cash_b[0]["cash"]
    return render_template("index.html", current_balance=cash, total_balance = cash)
else:
    new_rows_pt = []
    for row in rows_pt:
        new_rows_dict = {}
        quote = lookup(row["symbol"])
        new_rows_dict["symbol"] = quote["symbol"]
        new_rows_dict["name"] = quote["name"]
        new_rows_dict["shares"] = row["shares"]
        new_rows_dict["price"] = quote["price"]
        new_rows_dict["total"] = row["shares"] * quote["price"]

        new_rows_pt.append(new_rows_dict)

    cash_b = db.execute("SELECT cash FROM users WHERE id = :id",id = session["user_id"])
    cash = cash_b[0]["cash"]
    total_balance = cash
    for row in new_rows_pt:
        total_balance += row["total"]
    return render_template("index.html", rows_pt=new_rows_pt, current_balance=cash, total_balance = cash)
  • Can you reproduce the problem when running it locally in your VM? If so, what does the error message on the console say? You could edit the stack trace into your question. – Blauelf Sep 3 '18 at 8:55
0

Remember: when you register a new user, they do not have any stocks yet, so rows_pt is the empty set. Therefore, the for row in rows_pt: has no rows to process, does not execute, and "falls through". When that happens, it does not encounter a return, as the error message from check50 (and in your flask terminal) is describing. There may be other problems in the code. The flask terminal will give you feedback when errors are encountered.

EDIT: [based on comments and reposted code] I created a repro app with the new index and register functions pasted here. They performed as I expected, did not give an "Internal Server Error" and passed the register tests in check50. Is it possible you tested and check50'd before you saved the changes to application.py?

A quick primer on the flask log (built from experience).

You will see the flask log in the terminal from which you executed flask run. It always starts out with 5 or 6 info lines ending with * Restarting with stat. Entries generated from the app or the server will be logged after that. And remember when you save application.py in the editor, it will automatically respawn flask, so the last * Restarting with stat in the output is the most recent. Warning: when you switch to the flask terminal the last line posted to the log may not be the last line you can see on the screeen. Make sure you scroll to the bottom of the terminal to see it all.

4 types of entries you may encounter in the log are:

  • INFO:werkzeug:{ip} - - [{date time}] "GET / HTTP/1.1" 302 - This "GET / HTTP/1.1" 302 is saying
    server received a GET request for app route / using protocol HTTP/1.1 which returned a status code of 302
  • DEBUG:cs50:SELECT cash FROM users WHERE id = 26. This displays a db.execute call, with appropriate substitution of bound parameters. This can be a great troubleshooting tool, since you could copy/paste the sql into phpLiteAdmin or sqlite3 and review the results.
  • ERROR:flask.app:Exception..... This message is followed by a block of information, (the python Traceback) and one will be generated whenever you get an "Internal Server Error". As with all python Tracebacks, you need to go to the end of the block to find the actual error, and then work backwards to find where the error was generated.
  • ERROR:werkzeug:Error on request: I find these errors always accompany (follow) an ERROR:flask.app:Exception. It has something to do with the errorhandler defined in application.py and quite honestly I generally ignore them, since the ERROR:flask.app:Exception usually has the info I need to troubleshoot.
| improve this answer | |
  • Thank you so much! Could you please let me know how to check the flask terminal for errors? – Issa Sep 4 '18 at 2:58
  • I have updated my code for index as above. However, when I run check50, it still give me the same error messages. And I tried to register after running flask run, it shows 500 internal server error. But I check the user table, there are two users in the table as I tried twice. I still don't know if the error is in my register code, or Index code, or both. Could you please let me know and point me to the right direction? I have no clue. Thank you! – Issa Sep 4 '18 at 3:33
  • I have edited more info in the answer. – DinoCoderSaurus Sep 4 '18 at 17:24
  • Thank you so much for your answer! It helped me a lot. The problem was in my index.html, after I fixed that, register works. Thank you for the tips for debugging! – Issa Sep 5 '18 at 2:44

You must log in to answer this question.

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