Hi I am trying to make the final project for CS50, I run command flask run and get a url, but get status 404 not found. I used very similar code for the last task on CS50 and it worked just fine. Please help. This is my code, and I do have all html files with correct paths.
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
import datetime
# Configure application
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# 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:///meals.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", 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"):
flash("You must provide a username!")
return render_template("login.html")
# Ensure password was submitted
elif not request.form.get("password"):
flash("You must provide a password!")
return render_template("login.html")
# 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")):
flash("invalid username and/or password")
return render_template("login.html")
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
# Redirect user to home page
return redirect("/homepage")
# 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 render_template("login.html")
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
# If method is POST
if request.method == "POST":
name = request.form.get("username")
password = request.form.get("password")
confirmation = request.form.get("confirmation")
# Personal touch - Require users’ passwords to have some number of letters, numbers, and/or symbols
password_symbols = ['!', '#', '$', '%', '.', '_', '&']
# Check if any fields are empty
if not name:
flash("You must provide a username!")
return render_template("register.html")
elif not password:
flash("You must provide a password!")
return render_template("register.html")
elif not confirmation:
flash("You must confirm tha password!")
return render_template("register.html")
# Require users’ passwords to be 8 char long and to have some number of letters, numbers, and/or symbols
if len(password) < 8:
flash("Password must be at least 8 characters long!")
return render_template("register.html")
if not any(char.isdigit() for char in password):
flash("Password must have at least one number!")
return render_template("register.html")
if not any(char.isupper() for char in password):
flash("Password must have at least one uppercase!")
return render_template("register.html")
if not any(char in password_symbols for char in password):
flash("must contain at least one symbol of following: ! # $ % . _ &")
return render_template("register.html")
# Check if password and confirmation match
if not password == confirmation:
flash("Password doesn't match", 400)
return render_template("register.html")
# Check if username is taken
rows = db.execute("SELECT username FROM users WHERE username = ?", name)
if len(rows) > 0:
flash("Username is taken", 400)
return render_template("register.html")
# Add the new user into the database
hash = generate_password_hash(password)
db.execute("INSERT INTO users (username, hash) VALUES(?,?)", name, hash)
# Remember which user has logged in
rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username"))
session["user_id"] = rows[0]["id"]
# Redirect user to home page
flash('Registered!')
return redirect("/homepage")
# If method is GET
else:
return render_template("register.html")
@app.route("/homepage")
def homepage():
return render_template("homepage.html")
I am using VS code on cloud, just as for all others tasks in cs50, I run flask run and get a link with no error messages. Than I follow that url and instead of the page the browser returns 404 Not Found
It worked. I fixed it,. For anyone having a similar issue: this was the problem. The homepage route should be only / like this:
@app.route("/")
def homepage():
return render_template("homepage.html")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.