Search code examples
pythonsqliteflaskweb-applicationsproject

Flask Web App link user with sqlite3 list problem


I am coding a bullying reports web app in python with flask and a database in sqlite3 with 3 lists usuarios, victimas and testigos. Table usuarios is to list all the users (schools) registered and the table victimas is to show all the reports made by students that involve a SPECIFIC SCHOOL. For example: Show all reports from school "Gonza". So when a school logs in it can see all the reports made but the problem is there i can't link the school name with the victims list.

I think the problem is in the session[user_id] in line 162 and then on line 232 when i try to hechos = db.execute("SELECT * FROM victimas WHERE escuela = :escuela", escuela=session["user_id"]) it causes a bug. I had two different error messages from the debugger that are stated below:

KeyError: 'user_id' in line 232 hechos = db.execute("SELECT * FROM victimas WHERE escuela = :escuela", escuela=session["user_id"])

Sometimes this error also appears

NameError: name 'escuela' is not defined in line 241, in tablatestigos return render_template("tablatestigos.html", escuela=escuela)

@app.route("/regescuela", methods=["GET", "POST"])
def register():
    session.clear()

    if request.method == "POST":
        if not request.form.get("username"):
            return apology("No ha introducido un nombre de usuario!")
        elif not request.form.get("password"):
            return apology("No ha introducido una contraseña!")
        elif request.form.get("password") != request.form.get("confirmation"):
            return apology("Las contraseñas no coinciden.")
    else:
        usumayu = request.form.get("username")
        return render_template("regescuela.html")
    result = db.execute("INSERT INTO usuarios (username, hash) VALUES(:username, :hash)", username= request.form.get("username").upper(), hash=generate_password_hash(request.form.get("password")))

    if not result:
        return apology("Este usuario ya existe! Prueba con otro!")
    session["user_id"] = result[0]["username"]
    flash("Registrado!")
    return redirect("/")





@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("Debe ingresar un nombre de usuario.", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("Debe ingresar una contraseña.", 403)

        # Query database for username
        rows = db.execute("SELECT * FROM usuarios WHERE username = :username",
                          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("Usuario o contraseña incorrectos", 403)

        # Remember which user has logged in
        session["user_id"] = rows[0]["username"]

        # 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("/victima", methods=["GET", "POST"])
def victima():
    if request.method == "POST":
        if not (request.form.get("nombreescuela" and "curso" and "box")):
            return apology("Debes completar todo el formulario.")
        if  not (len(request.form.get("curso")) == 2):
            return apology("Ingrese corectamente el curso (no mas de 2 digitos). El primero debe ser un numero y el segundo la letra de su division. Ejemplo: 5A  | (si su colegio no tiene division ingrese el numero acompañado de una x. Ejemplo: 5x) | ")
        if not ((request.form.get("curso")[0] == "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9") and (request.form.get("curso")[1].isalpha())):
            return apology("Ingrese el curso correctamente. No se aceptan mas de 2 digitos. El primero debe ser un numero y el segundo la letra de su division. Ejemplo: 5A  | (si su colegio no tiene division ingrese el numero acompañado de una x. Ejemplo: 5x) | ")

        db.execute("INSERT INTO victimas (escuela, curso, hecho) VALUES(:escuela, :curso, :hecho)", escuela=request.form.get(
            "nombreescuela"), curso=request.form.get("curso").upper(), hecho=request.form.get("box"))

        flash("Formulario enviado con éxito!")

        return redirect("/")
    else:
        return render_template("victima.html")

@app.route("/testigo", methods=["GET", "POST"])
def testigo():
    if request.method == "POST":
        if not (request.form.get("nombreescuela" and "curso" and "victima" and "box")):
            return apology("Debes completar todo el formulario.")
        if  not (len(request.form.get("curso")) == 2):
            return apology("Ingrese corectamente el curso. No mas de 2 digitos. El primero debe ser un numero y el segundo la letra de su division. Ejemplo: 5A  | (si su colegio no tiene division ingrese el numero acompañado de una x. Ejemplo: 5x) | ")
        if not ((request.form.get("curso")[0] == "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9") and (request.form.get("curso")[1].isalpha())):
            return apology("Ingrese el curso correctamente. No se aceptan mas de 2 digitos. El primero debe ser un numero y el segundo la letra de su division. Ejemplo: 5A |  (si su colegio no tiene division ingrese el numero acompañado de una x. Ejemplo: 5x) | ")

        db.execute("INSERT INTO testigos (escuela, curso, victima, hecho) VALUES(:escuela, :curso, :victima, :hecho)", escuela=request.form.get(
            "nombreescuela"), curso=request.form.get("curso").upper(), victima=request.form.get("victima"), hecho=request.form.get("box"))

        flash("Formulario enviado con éxito!")

        return redirect("/")
    else:
        return render_template("testigo.html")



@app.route("/reportesrecibidos", methods=["GET", "POST"])
@login_required
def reportesrecibidos():
    return render_template("reportesrecibidos.html")

@app.route("/tablavictimas")
@login_required
def tablavictimas():
    hechos = db.execute("SELECT * FROM victimas WHERE escuela = :escuela", escuela=session["user_id"])
    return render_template("tablavictimas.html", escuela=escuela)

@app.route("/tablatestigos")
@login_required
def tablatestigos():
    hechos = db.execute("SELECT * FROM testigos WHERE escuela = :escuela", escuela=session["user_id"])
    return render_template("tablatestigos.html", escuela=escuela)

Error messages:

KeyError: 'user_id' in line 232 hechos = db.execute("SELECT * FROM victimas WHERE escuela = :escuela", escuela=session["user_id"])

Sometimes this error also appears

NameError: name 'escuela' is not defined in line 241, in tablatestigos return render_template("tablatestigos.html", escuela=escuela)


Solution

  • You have this error:

    NameError: name 'escuela' is not defined in line 241, in tablatestigos return render_template("tablatestigos.html", escuela=escuela)

    because escuela is not defined. I think the error message is very clear. Anyway, to solve this problem, you need to define escuela like this:

    @app.route("/tablatestigos")
    @login_required
    def tablatestigos():
        escuela = session["user_id"]
        hechos = db.execute("SELECT * FROM testigos WHERE escuela = :escuela",
        escuela=escuela)
        return render_template("tablatestigos.html", escuela=escuela)
    

    The second error:

    KeyError: 'user_id' in line 232 hechos = db.execute("SELECT * FROM victimas WHERE escuela = :escuela", escuela=session["user_id"])

    is raised because session["user_id"] does not exist. There are many reasons for this: First, may be the user is not logged in. So you may have a problem in the decorator @login_required. Second, may be you did not define a secret_key for your application. In this case, you will lost your session content after every page refresh. To solve this issue, you need to define a secret_key for your application in the main file:

    app = Flask('application')
    app.secret_key = "some secret key"
    

    Note that there are more secure solution to define a secret_key for your application but this is the easiest solution.