How can I reset a session without a separate @app.route in flask?

Question:

For my class, we’re tasked with making a simple game page to earn gold, while only using a maximum of 2 @app.routes. One of the bonus tasks is to make a Reset button that’ll start the game over, but I can’t quite figure out how to do that using the existing routes. I’ve tried changing the method to ‘get’ for the button and adding ‘GET’ to the main route but it didn’t work the way I thought it would

Any tips on how I might be able to achieve this are greatly appreciated. Python and HTML are included for reference.

 @app.route('/')
def index():
    if 'gold' not in session:
        session['gold'] = 0
        session['earnings'] = []
        session['losses'] = []
    if request.method == 'GET':
        session.clear
    print(session['gold'], "in the bank")
    return render_template('index.html')

@app.route('/process_money', methods=['POST'])
def process_money():
    print(request.form)
    if request.form['get_gold'] == 'rice_paddy':
        temp = random.randint(10,20)
        session['gold'] += temp
        earning = session['earnings']
        earning.append(f"Your hard work paid off, you earned {temp} gold from the rice paddy!")
        session['earnings'] = earning
        print(f"Your hard work paid off, you earned {temp} gold from the rice paddy!")
    if request.form['get_gold'] == 'hideout':
        temp = random.randint(5,10)
        session['gold'] += temp
        earning = session['earnings']
        earning.append(f"After rummaging around in the cushions, you found {temp} gold in the hideout!")
        session['earnings'] = earning
        print(f"After rummaging around in the cushions, you found {temp} gold in the hideout!")
    if request.form['get_gold'] == 'castle':
        temp = random.randint(2,5)
        session['gold'] += temp
        earning = session['earnings']
        earning.append(f"While no one was looking, you stole {temp} gold from the castle!")
        session['earnings'] = earning
        print(f"While no one was looking, you stole {temp} gold from the castle!")
    if request.form['get_gold'] == 'dice_den':
        temp = random.randint(-50,50)
        if temp >= 0:
            session['gold'] += temp
            earning = session['earnings']
            earning.append(f"Nice! You gained {temp} gold while gambling at the dice den!")
            session['earnings'] = earning
            print(f"Nice! You gained {temp} gold while gambling at the dice den!")
        elif temp <= 0:
            session['gold'] += temp
            losses = session['losses']
            losses.append(f"Aww, too bad! You lost {temp} gold while gambling at the dice den!")
            session['losses'] = losses
            print(f"Aww, too bad! You lost {temp} gold while gambling at the dice den!")
    return redirect('/')

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

<body>
    <div id="main" class="container bg-dark">
        <label for="your_gold" class="text-light" style="margin-top: 1.5rem;">Your Gold:</label>
        <input type="number" value="{{session['gold']}}">
        <div class="d-flex">
            <div class="container">
                <form method="post" action="/process_money">
                    <input type="hidden" name="get_gold" value="rice_paddy">
                    <h4>Rice Paddy</h4>
                    <p>(earns 10-20 gold)</p>
                    <input type="submit" name="rice_paddy" id="rice_paddy" value="Earn Gold!">
                </form>
            </div>
            <div class="container">
                <form method="post" action="/process_money">
                    <input type="hidden" name="get_gold" value="hideout">
                    <h4>Hideout</h4>
                    <p>(earns 5-10 gold)</p>
                    <input type="submit" name="hideout" id="hideout" value="Find Gold!">
                </form>
            </div>
            <div class="container">
                <form method="post" action="/process_money">
                    <input type="hidden" name="get_gold" value="castle">
                    <h4>Shiro</h4>
                    <p>(earns 2-5 gold)</p>
                    <input type="submit" name="castle" id="castle" value="Steal Gold!">
                </form>
            </div>
            <div class="container">
                <form method="post" action="/process_money">
                    <input type="hidden" name="get_gold" value="dice_den">
                    <h4>Dice Den</h4>
                    <p>(earns/takes 0-50 gold)</p>
                    <input type="submit" name=dice_den id=dice_den value="Gamble Gold!">
                </form>
            </div>
        </div>
        <h5 class="text-light">Activities:</h5>
        <div id="activities" class="container">
            <ul>
                    {% for earning in session['earnings'] %}
                        <li class="text-success">{{earning}}</li>
                    {% endfor %}
                    {% for loss in session['losses'] %}
                        <li class="text-danger">{{loss}}</li>
                    {% endfor %}
            </ul>
        </div>
        <a method='get' class="btn btn-danger" style="border: 2px solid black; width: auto; margin-bottom: 20px;" href="/">Reset</a>
    </div>
</body>
</html>

Asked By: Brad

||

Answers:

You can do exactly what you’ve been doing to allow the four game buttons to use one same @app.route. You can make it another <form> and just set get_gold to, say, reset_game. The Python code should then set the gold to 0 and set earnings and losses to an empty list.

@app.route('/process_money', methods=['POST'])
def process_money():
    ...  # Process the four main game buttons
    if request.form['get_gold'] == 'reset_game':  # Reset the game
        session['gold'] = 0
        session['earnings'] = []
        session['losses'] = []
        print('Reset game gold,earnings,losses')
    return redirect('/')

And in your HTML file, add these lines somewhere:

<form method="post" action="/process_money">
    <input type="hidden" name="get_gold" value="reset_game">
    <h4>Reset game!</h4>
    <p>(resets your game)</p>
    <input type="submit" value="Reset!">
</form>
Answered By: David
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.