簡體   English   中英

如何在 flask 中沒有單獨的 @app.route 的情況下重置 session?

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

對於我的 class,我們的任務是制作一個簡單的游戲頁面來賺取金幣,同時最多只使用 2 個@app.routes。 獎勵任務之一是制作一個重置按鈕以重新開始游戲,但我不太清楚如何使用現有路線來做到這一點。 我嘗試將按鈕的方法更改為“get”並將“GET”添加到主路由,但它並沒有像我想象的那樣工作

非常感謝任何關於我如何能夠實現這一目標的提示。 包含 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>

您可以完全按照您一直在做的事情來允許四個游戲按鈕使用相同的@app.route 您可以將其設為另一個<form>並將get_gold設置為,例如reset_game 然后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('/')

在您的 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