Session not getting updated in Python - Flask

46 views Asked by At

I'm running my HTML code in Python - Flask.

treasure_hunt.html:

<!DOCTYPE html>
<html>
<head>
    <title>Attractive Pop-up Example</title>
    <style>
        /* Styles for the overlay */
        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* Styles for the pop-up */
        .popup {
            background: linear-gradient(135deg, #ff6f61, #ff8e64);
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
            text-align: center;
            max-width: 400px;
            width: 80%;
        }

        .popup h2 {
            font-size: 28px;
            color: #fff; /* White color for the heading */
            margin-bottom: 20px;
        }

        .popup p {
            font-size: 18px;
            color: #fff; /* White color for the text */
            margin-bottom: 20px;
        }

        .popup input[type="text"] {
            padding: 10px;
            width: 80%;
            margin: 20px 0;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            max-width: 100%;
        }

        .popup button {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: #fff;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 18px;
            transition: background 0.3s;
        }

        .popup button:hover {
            background: linear-gradient(135deg, #0056b3, #003a73); /* Darker blue gradient on hover */
        }

        /* Optional: Add a subtle animation */
        .popup {
            animation: fadeIn 0.5s;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }
    </style>
</head>
<body>

<!-- The overlay and pop-up container -->
<form class="overlay" id="popupOverlay">
    <div class="popup">
        <h2>{{ heading }}</h2>
        <p>{{ clue }}</p>
        <input type="text" id="password" placeholder="Enter something">
        <button id="popupButton" type="submit">Submit</button>
        <input type="hidden" id="currentIndex" value="0">
    </div>
</form>

<script>
    // JavaScript to display the pop-up on page load
const popupOverlay = document.getElementById('popupOverlay');
const currentIndexInput = document.getElementById('currentIndex');

// Show the pop-up on page load
window.addEventListener('load', () => {
    popupOverlay.style.display = 'flex';
});

// Optional: Close the pop-up when the escape key is pressed
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        popupOverlay.style.display = 'none';
    }
});

document.getElementById('popupButton').addEventListener('click', () => {
    const password = document.getElementById('password').value;
    const currentIndex = parseInt(currentIndexInput.value);

    fetch('/check_password', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `password=${password}`,
    })
        .then((response) => response.json())
        .then((data) => {
            if (data.success) {
                // Update the clue and current index
                currentIndexInput.value = currentIndex + 1;
                document.querySelector('h2').textContent = 'I++ - Treasure Hunt';
                document.querySelector('p').textContent = data.clue;
            }
        })
        .catch((error) => {
            console.error('Error:', error);
        });
});

</script>

</body>
</html>

python code:

from flask import Flask, render_template, request, jsonify, session
from pyngrok import ngrok
import random

app =  Flask(__name__, template_folder='/content', static_url_path='/static', static_folder='/content')

# Set the secret key
app.secret_key = 'scan_and_seek'

public_url = ngrok.connect(addr='localhost:5000')
print('Public URL:', public_url)

# Your data
clues = [... ] #clues

codes = [...] #codes

answers = [...]#answers

passwords = [...]#passwords

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/start')
def start():
    print("Session in start:", session)
    if 'unique_indices' not in session:
        session['unique_indices'] = list(range(len(clues)))
        session['num']=0
        random.shuffle(session['unique_indices'])

    if not session['unique_indices']:
        return render_template('success.html', heading='I++ - Scan and Seek', clue="completed")

    current_index = session['unique_indices'][0]
    print('Current index in start function:', current_index)
    print("Session modified :",session.modified)
    print('Session in start function:', session['unique_indices'])
    print("Answer:", answers[current_index])
    print("Password:", passwords[current_index])
    clue = clues[current_index]
    return render_template('treasue_hunt.html', heading='TH', clue=clue, code='Code to unlock: ' + codes[current_index])

@app.route('/check_password', methods=['POST'])
def check_password():
    if 'unique_indices' not in session:
        session['unique_indices'] = list(range(len(clues)))
        random.shuffle(session['unique_indices'])

    if not session['unique_indices']:
        return render_template('success.html', heading='TH', clue="completed")

    current_index = session['unique_indices'][0]
    required_password = passwords[current_index]
    entered_password = request.form.get('password').strip()

    if entered_password == required_password:
        d = session['unique_indices']
        d.pop(0)
        session['unique_indices'] = d
        session['num']=1
        session.modified = True

        if not session['unique_indices']:
            return render_template('success.html', heading='TH', clue="completed")

        next_index = session['unique_indices'][0]
        next_clue = clues[next_index]
        print("Session after successful password:", session)
        return jsonify({'success': True, 'clue': next_clue, 'code': 'Code to unlock: ' + codes[next_index]})
    else:
        print("Incorrect password entered.")
        return jsonify({'success': False})

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

output:

Session in start: <SecureCookieSession {}>
Current index in start function: 1
Session modified : True
Session in start function: [1, 7, 9, 4, 5, 0, 6, 8, 2, 3]
Answer: B
Password: 8877
INFO:werkzeug:127.0.0.1 - - [27/Oct/2023 16:47:59] "POST /check_password HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [27/Oct/2023 16:47:59] "GET /start HTTP/1.1" 200 -
Session after successful password: <SecureCookieSession {'num': 1, 'unique_indices': [7, 9, 4, 5, 0, 6, 8, 2, 3]}>
Session in start: <SecureCookieSession {'num': 0, 'unique_indices': [1, 7, 9, 4, 5, 0, 6, 8, 2, 3]}>
Current index in start function: 1
Session modified : False
Session in start function: [1, 7, 9, 4, 5, 0, 6, 8, 2, 3]
Answer: B
Password: 8877
INFO:werkzeug:127.0.0.1 - - [27/Oct/2023 16:48:21] "POST /check_password HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [27/Oct/2023 16:48:21] "GET /start HTTP/1.1" 200 -
Incorrect password entered.
Session in start: <SecureCookieSession {'num': 1, 'unique_indices': [7, 9, 4, 5, 0, 6, 8, 2, 3]}>
Current index in start function: 7
Session modified : False
Session in start function: [7, 9, 4, 5, 0, 6, 8, 2, 3]
Answer: S
Password: 9807

My problem is the session is not getting updated in /start. In the /check_password, it is updated but not reflected in /start.

If correct code is entered as input, still the same clue appears. The second time, if the wrong clue is entered or if the no input is entered, the next clue appears. Here, the session variable gets updated only in the 2nd time not on the 1st time.

I'm running this code in Google Colab.

May I know the reason for this?

0

There are 0 answers