简体   繁体   English

如何在 flask 中没有单独的 @app.route 的情况下重置 session?

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

For my class, we're tasked with making a simple game page to earn gold, while only using a maximum of 2 @app.routes.对于我的 class,我们的任务是制作一个简单的游戏页面来赚取金币,同时最多只使用 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我尝试将按钮的方法更改为“get”并将“GET”添加到主路由,但它并没有像我想象的那样工作

Any tips on how I might be able to achieve this are greatly appreciated.非常感谢任何关于我如何能够实现这一目标的提示。 Python and HTML are included for reference.包含 Python 和 HTML 以供参考。

 @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>

You can do exactly what you've been doing to allow the four game buttons to use one same @app.route .您可以完全按照您一直在做的事情来允许四个游戏按钮使用相同的@app.route You can make it another <form> and just set get_gold to, say, reset_game .您可以将其设为另一个<form>并将get_gold设置为,例如reset_game The Python code should then set the gold to 0 and set earnings and losses to an empty list.然后losses代码应将gold设置为 0,并将earnings设置为空列表。

@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:在您的 HTML 文件中,在某处添加以下行:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM