0

On my website for my final project I am able to enter the user info on the website, but the information is not being inserted into the sql table. I feel that I am not understanding something very straightforward. Any help would be appreciated. My code is below:

import os

from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash

from helpers import apology, login_required, lookup, usd

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

# Custom filter
app.jinja_env.filters["usd"] = usd

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")

# Make sure API key is set
if not os.environ.get("API_KEY"):
    raise RuntimeError("API_KEY not set")


@app.route("/")
@login_required
def index():
    """Show exercise log"""
    return render_template("index.html")


@app.route("/train", methods=["GET", "POST"])
@login_required
def train():
    """Update exercise log"""

    if request.method == "POST":

        def __init__(user_id, date, exercise, time, heart_rate, grade, created_on):
            user_id = user_id
            date = date
            exercise = exercise
            time = time
            heart_rate = heart_rate
            grade = grade
            created_on = created_on

            db.execute("INSERT INTO training "
                    "(user_id, date, exercise, time, heart_rate, grade, created_on) "
                    "VALUES (:user_id, :date, :exercise, :time, :heart_rate, :grade, :created_on)",
                    user_id=session["user_id"],
                    date=date,
                    exercise=exercise,
                    time=time,
                    heart_rate=heart_rate,
                    grade=grade,
                    created_on=datetime.utcnow()
            )
        return redirect("/")

    else:
        return render_template("train.html", train = train)

@app.route("/check", methods=["GET"])
def check():
    """Return true if username available, else false, in JSON format"""
    username = request.args["username"]

    if len(username) == 0:
        return jsonify(False)

    rows = db.execute("SELECT * FROM users WHERE username = :username",
                      username=username)
    if rows:
        return jsonify(False)

    return jsonify(True)

@app.route("/history")
@login_required
def history():
    """Show history of exercise"""
    result = db.execute("SELECT exercise, time, heart_rate, created_on FROM training "
                        "WHERE user_id = :user_id ORDER BY created_on DESC",
                        user_id = session["user_id"])
    history = [(row["exercise"], row["time"], row["heart_rate"], row["created_on"]) for row in result]
    return render_template("history.html", history = history)


@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("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 = :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("invalid username and/or password", 403)

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

        # 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("/register", methods=["GET", "POST"])
def register():
    """Register user"""
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        password_confirmation = request.form.get("confirmation")

        #Ensure username was submitted
        if not username:
            return apology("Username required", 400)

        #Ensure password was submitted
        if not password:
            return apology("Password required")
        if not password == password_confirmation:
            return apology("Passwords you entered do not match")

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

        if rows:
            return apology("Username already exists")

        db.execute("INSERT INTO users (username, hash) VALUES (:username, :hash)",
            username=username,
            hash=generate_password_hash(password),
        )

        return redirect("/login")
    elif request.method == "GET":
        return render_template("register.html")


def errorhandler(e):
    """Handle error"""
    if not isinstance(e, HTTPException):
        e = InternalServerError()
    return apology(e.name, e.code)


# Listen for errors
for code in default_exceptions:
    app.errorhandler(code)(errorhandler)

I don't get any error messages in the terminal:

Serving Flask app "application.py" (lazy loading)
 * Environment: development
 * Debug mode: off
 * Running on https://77a97a25-a09f-4c37-b6f6-02760f980bb3-ide.cs50.xyz:8080/ (Press CTRL+C to quit)
 * Restarting with stat
INFO:werkzeug: - - [27/Oct/2020 16:29:57] "GET / HTTP/1.0" 302 -
INFO:werkzeug: - - [27/Oct/2020 16:29:57] "GET /login HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:29:57] "GET /static/styles.css HTTP/1.0" 200 -
DEBUG:cs50:SELECT * FROM users WHERE username = 'ed'
INFO:werkzeug: - - [27/Oct/2020 16:30:01] "POST /login HTTP/1.0" 302 -
INFO:werkzeug: - - [27/Oct/2020 16:30:01] "GET / HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:30:01] "GET /static/styles.css HTTP/1.0" 200 -
DEBUG:cs50:SELECT exercise, time, heart_rate, created_on FROM training WHERE user_id = 2 ORDER BY created_on DESC
INFO:werkzeug: - - [27/Oct/2020 16:30:03] "GET /history HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:30:03] "GET /static/styles.css HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:30:04] "GET /train HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:30:04] "GET /static/styles.css HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:30:05] "GET / HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:30:05] "GET /static/styles.css HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:30:06] "GET /train HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:30:06] "GET /static/styles.css HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:30:21] "POST /train HTTP/1.0" 302 -
INFO:werkzeug: - - [27/Oct/2020 16:30:21] "GET / HTTP/1.0" 200 -
INFO:werkzeug: - - [27/Oct/2020 16:30:21] "GET /static/styles.css HTTP/1.0" 200 -

Thank you!

3
  • Did you try testing your insert query using phpmyadmin to verify its correctness? – Cliff B Oct 27 '20 at 18:54
  • I'm not sure how to do that. However, I am able to get data added to the 'users' table, but not the 'training' table with the code above. – Leonidas Smiley Oct 27 '20 at 20:50
  • Can you refactor out the def init part of your code? I do not think Flask supports nested function. – EddyBeor Dec 9 '20 at 20:20

You must log in to answer this question.

Browse other questions tagged .