1

I've been building the flask program underneath:

app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
DATABASE = "qa_database.db"

def get_db():
    db = getattr(g, "_database", None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    return db

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, "_database", None)
    if db is not None:
        db.close()

@app.route("/", methods=["GET", "POST"])
def home():
    db = get_db()
    cursor = db.cursor()
    # Initialize session variables if they don't exist
    if 'counter' not in session:
        session['counter'] = 0
    if 'incorrect_types' not in session:
        session['incorrect_types'] = []

    if request.method == "POST":
        # Check if the user has made a choice on question types
        if 'choice' in request.form:
            if request.form['choice'] == 'practice':
                session['practice_wrong'] = True
            else:
                session['practice_wrong'] = False
            
            session['counter'] = 0  # Reset the counter after making a choice
            session['incorrect_types'] = []  # Reset the incorrect types
            
            # Debug statement
            print("practice_wrong set to:", session['practice_wrong'])
            
            return redirect(url_for('home'))
        # Get user answers from the form
        answer1 = request.form.get("answer1")
        answer2 = request.form.get("answer2")

        # Retrieve questions, correct answers, and types from session
        question1 = session.get("question1")
        correct_answer1 = session.get("correct_answer1")
        question1_type = session.get("question1_type")
        # Initialize message
        message = ""
        # Initialize a flag to indicate if the choice buttons should be shown
        show_choice = False
        if question1 and correct_answer1:
            # Check if answers are correct and log incorrect types
            if answer1.lower() == correct_answer1.lower():
                message = "Well Done! You got both correct."
            elif answer1.lower() != correct_answer1.lower():
                session['incorrect_types'].append(question1_type)
                message = "Oops! You got both wrong."
                message += f"<br><br>Correct Answer: {correct_answer1}<br>Your Answer: {answer1}"        
        # Increment the counter
        session['counter'] += 1

        # Check if it's time to offer the user a choice
        if session['counter'] % 3 == 0:
            show_choice = True
            # Get the unique topics the user got wrong
            unique_incorrect_types = list(set(session['incorrect_types']))
            # Create a message based on the number of topics
            if unique_incorrect_types:
                topics_list = ", ".join(unique_incorrect_types)
                message = f"You've been getting questions wrong in topics: {topics_list}. Want to practice on these topics?"
                print(unique_incorrect_types)  
            else:
                message = "Want to practice on the topics you're failing?"

        # Render the home page with the message and choice buttons if needed
        return render_template("home.html", message=message, submitted=True, next_question=not show_choice, show_choice=show_choice)
    else:
        print("DEBUG STATEMENT", session['incorrect_types']) #ARRAY IS EMPTY 
        if session.get('practice_wrong', False) and session['incorrect_types']:
            # Convert the list of incorrect types to a set to remove duplicates, then back to a list
            types_list = list(set(session['incorrect_types']))
            # Create a string of placeholders that match the length of types_list
            placeholders = ','.join('?' * len(types_list))
            # Execute the query with the list of types
            cursor.execute(f"SELECT question, correct_answer, type FROM Questions WHERE type IN ({placeholders}) ORDER BY RANDOM()", types_list)
        else:
            cursor.execute("SELECT question, correct_answer, type FROM Questions ORDER BY RANDOM()")
        
        questions = cursor.fetchall()

        if len(questions) >= 2:
            # Store questions, correct answers, and types in session
            question1, correct_answer1, question1_type = questions[0]
            question2, correct_answer2, question2_type = questions[1]
            session["question1"] = question1
            session["correct_answer1"] = correct_answer1
            session["question1_type"] = question1_type
            # Render the home page with the random questions
            return render_template("home.html", question1=question1, question2=question2, submitted=False, next_question=False)
        else:
            return "There are not enough questions in the database."

if __name__ == "__main__":
    app.run(debug=True)

Here is the HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Question and Answer</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='homeCSS.css') }}">
</head>
<body>
    <h1>Answer the Questions</h1>
    {% if not submitted %}
    <form method="POST">
        <p>{{ question1 }}</p>
        <input type="text" name="answer1" required>
        <br>
        <p>{{ question2 }}</p>
        <input type="text" name="answer2" required>
        <br>
        <br>
        <input type="submit" value="Submit">
    </form>
    {% endif %}
    {% if message %}
        <p>{{ message|safe }}</p>
    {% endif %}
    {% if next_question %}
        <a href="/">Next Question</a>
    {% endif %}
    {% if show_choice %}
    <p>{{ message|safe }}</p>
    <form method="POST">
        <input type="submit" name="choice" value="practice">
        <input type="submit" name="choice" value="random">
    </form>
{% endif %}
</body>
</html>

This Flask script gets a random question from a database and after every 3 questions the user is asked if they want to go into either "practice" or "random mode". In practice mode, they are only asked questions based on the question types they got wrong in the past (in the incorrect_types array).

The issue is that after the incorrect types are correctly appended into the session array (I've tested this works), on the DEBUG statement print("DEBUG STATEMENT", session['incorrect_types']), the array is shows as empty even through values have been appended into it.

I would be grateful if someone could guide me in being able to fix my session variable. Thanks.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.