I'm programming in Python and I'm using the Flask framework. I'm having a problem with the redirect()
function. It simply doesn't work for some unknown reason. It doesn't cast an error, or throw an error into the console. It doesn't mention anything in the terminal, either. I need it to work for my login system where if you input to register doesn't match the validation, to redirect you back to the page and display the error (through sessions.)
I've tried using different ways I've found on the internet and by reading source code. I've tried using app.redirect()
method instead of flask.redirect()
the global function. Here is my code:
from flask import Flask, request, render_template, session, redirect
from flask_session import Session
from security_manager import password_hash, password_check
from validate_email_address import validate_email
import json
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
@app.route("/")
def index():
return "<!DOCTYPE html><a href=\"/signup\">Redirect to Sign-up page</a>"
@app.route("/signup")
def signup():
try:
message = session["signup_error"]
return render_template("signup.htm") + (
"" if "signup_error" not in session else
"<p style=\"color:red;\">" + message + "</p>"
)
except KeyError:
return render_template("signup.htm")
@app.route("/control-signup", methods=["POST"])
def control_signup():
display_name = request.form["display_name"] # Use .args for GET requests,
# .form for POST ones
display_name = secure_signal(display_name)
# Validating username (handle)
username = request.form["username"]
if not username_valid(username):
session["signup_error"] = "Username can only include lowercase" \
" letters a–z, uppercase letters" \
" A–Z, digits 0–9 or an" \
" underscore and must be 4 to 16" \
" characters long."
redirect("/signup")
elif not username_available(username):
session["signup_error"] = "Username is already taken."
redirect("/signup")
# Validating E-Mail address
email = request.form["email"]
if not validate_email(email):
session["signup_error"] = "E-Mail address appears to be invalid."
redirect("/signup")
# Checking if password confirmation is correct
password = request.form["password"]
password_confirmation = request.form["password_confirmation"]
if password != password_confirmation:
session["signup_error"] = "Passwords don't match."
redirect("/signup")
# Checking if password is strong enough.
if not 8 <= len(password):
session["signup_error"] = "Password must at least be 8 characters" \
" long."
redirect("/signup")
digits = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
has_digit = False
for digit in digits:
if digit in password: # If the password has a digit.
has_digit = True
break
if not has_digit:
session["signup_error"] = "Password must include a digit."
redirect("/signup", code=302)
# Everything is fine. Create the account.
users_db = json.load(open("users.json", "r"))
# Hashing the password
hashed_password = password_hash(password)
user = {
"username": username,
"email": email,
"password": hashed_password,
"display_name": display_name,
"bio": ""
}
users_db.append(user)
with open("users.json", "w") as file:
file.write(json.dumps(users_db, indent=4))
return render_template("signup_complete.htm")
@app.route("/log-in")
def log_in():
if "login_error" in session:
return render_template("log-in.htm") + ("<span style=\"color:red\">" +
session["login_error"] +
"</span>")
else:
return render_template("log-in.htm")
@app.route("/control-login", methods=["POST"])
def control_login():
email_or_username = request.form["email_or_username"]
password = request.form["password"]
login_meth = request.form["login_meth"]
user_db = json.load(open("users.json", "r"))
for user in user_db:
if user["email" if login_meth == "email" else "username"]\
== email_or_username and\
password_check(password, user["password"]):
session["is_logged_in"] = True
if session["is_logged_in"]:
return "<h1>Successfully logged you in</h1>"
else:
session["login_error"] = "Username, E-Mail or password incorrect."
redirect("/log-in")
def secure_signal(message: str) -> str:
return (message
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("'", "'")
.replace("\"", """)
)
def username_valid(username: str) -> bool:
"""
:param username: Username you want to validate.
:return: Boolean "True" if the username is valid and "False if the
username is invalid
"""
# Checking if the username has illegal characters
legal_characters = ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
"3", "4", "5", "6", "7", "8", "9", "_")
for letter in username:
if letter not in legal_characters:
return False
# Checking if username is short/long enough
if not 4 <= len(username) <= 16:
return False
def username_available(username: str) -> bool:
# Checking if the username is already taken
users_db = json.load(open("users.json", "r"))
for user in users_db:
if user["username"].lower() == username.lower():
# I type ".lower()" because I don't want the usernames to be
# case-sensitive.
return False
del users_db
return True
def email_available(email: str) -> bool:
# Checking if the username is already taken
users_db = json.load(open("users.json", "r"))
for user in users_db:
if user["email"].lower() == email.lower():
# I type ".lower()" because I don't want the usernames to be
# case-sensitive.
return False
del users_db
return True
if __name__ == "__main__":
app.run(debug=True)
from flask import Flask, flash, redirect, render_template, request, session, abort, send_file
import os
import sqlite3
app = Flask(__name__)
# -- Connect to Databse --
def connect():
connection = sqlite3.connect("database.db")
cursor = connection.cursor()
return connection, cursor
# -- Home Page --
@app.route('/')
def home():
if "username" in session:
username = session["username"]
else:
username = "user"
return render_template("welcome.html",username=username)
# -- Login --
@app.route('/login', methods=['POST', 'GET'])
def login():
incorrect_info=False
if request.method == "POST":
username = request.form['username']
password = request.form['password']
connection, cursor = connect()
cursor.execute(f'SELECT "password" FROM users WHERE username = "{username}"')
from_db = cursor.fetchone()
connection.close()
if from_db is None or password != from_db[0]:
incorrect_info = True
return render_template("login.html", incorrect=incorrect_info)
else:
session["username"] = username
return redirect("/")
else:
return render_template("login.html", incorrect=incorrect_info)
# -- Create Account --
@app.route('/create_account', methods=['POST', 'GET'])
def create_account():
if request.method == "POST":
username = request.form['username']
password = request.form['password']
email = request.form['email']
if username != "" or password != "" or email != "":
user_info = (username, password, email)
connection, cursor = connect()
cursor.execute('INSERT INTO "users" (username, password, email) VALUES (?, ?, ?)', user_info)
connection.commit()
connection.close()
session['username'] = username
return redirect('/')
else:
return render_template("create.html")
from flask_session import Session
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
def db_connection():
con = None
try:
con = sqlite3.connect('user.db')
except Exception as e:
print(e)
return con
@app.route('/menu', methods=["POST", "GET"])
def checkavailibility():
if request.method == 'POST':
session["numberofpeople"] = request.form.get('membercount')
session["date"] = request.form.get('date')
session["visitingtime"] = request.form.get('visitingtime')
con = db_connection()
cursor = con.cursor
cursor.execute("SELECT * FROM Reserve")
pop = "sorry Reserve is not available"
li = []
for i in cursor:
if i[-1] is None and i[1] is None:
li.append(i[0])
if session.get('usernamelogin') == i[-1]:
tablenumber = i[0]
datebook = i[2]
timebook = i[3]
con.close()
return render_template('reserve.html', booked=session.get('namelogin'), tablenumber=tablenumber, datebook=datebook, timebook=timebook, username = session.get('usernamelogin'), namelogin=session.get('namelogin'), email=session.get('emaillogin'))
con.close()
return render_template('reserve.html' list=li, pop=pop, username=session.get('usernamelogin'), namelogin=session.get('namelogin'), email=session.get('emaillogin'))
return render_template('login.html')
@app.route('/tablebook' methods=['GET','POST'])
def booktable():
if request.method == 'POST':
tablename = request.form.get('tablename')
con = db_connection()
cursor = con.cursor()
cursor.execute('SELECT * FROM tabledata')
for i in cursor:
if i[0] == tablename:
update = "update tabledata set numberofpeople=?, date=?, visittime=?, username=? where tablename=?"
n1= session.get('numberofpeople')
n2= session.get('date')
n3= session.get('visitingtime')
n4= session.get('usernamelogin')
cursor.execute(update, (n1,n2,n3,n4, tablename))
con.commit()
con.close()
session.clear()
return render_template('tablebook.html')
return render_template('menu.html')
if __name__ == "__main__":
app.secret_key = os.urandom(12)
app.run(debug=True, host="0.0.0.0", port=80)