You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask应用中实现点击按钮单次随机显示列表元素且不重复

Got it, let's fix this problem properly. The issue with just reloading the page is that you're resetting the state every time—so we need to keep track of which items have already been shown using session storage (since it persists between requests for the same user). Here's a complete working solution:

Solution: Track Shown Items with Session Storage

Step 1: Update your app.py

from flask import Flask, render_template, session, redirect, url_for, request
import random

app = Flask(__name__)
# Required to use session - set a secure secret key in production!
app.secret_key = 'your-secure-random-secret-key'

# Your original item list
ITEM_LIST = ['item 1', 'item 2', 'item 3']

@app.route('/', methods=['GET', 'POST'])
def index():
    # Initialize session state on first visit
    if 'remaining_items' not in session:
        session['remaining_items'] = ITEM_LIST.copy()
        session['shown_items'] = []
    
    if request.method == 'POST':
        # Handle refresh button click
        if session['remaining_items']:
            # Pick a random item from remaining
            selected_item = random.choice(session['remaining_items'])
            # Remove it from remaining and add to shown list
            session['remaining_items'].remove(selected_item)
            session['shown_items'].append(selected_item)
            # Mark session as modified to save changes
            session.modified = True
            return redirect(url_for('index'))
        # If no items left, we'll show "finished" in the template
    
    # Pass data to template
    current_item = session['shown_items'][-1] if session['shown_items'] else None
    is_finished = not bool(session['remaining_items'])
    return render_template('index.html', current_item=current_item, is_finished=is_finished)

Step 2: Create a Template (templates/index.html)

<!DOCTYPE html>
<html>
<head>
    <title>Random Item Display</title>
</head>
<body>
    <h2>
        {% if is_finished %}
            Finished! All items have been displayed.
        {% elif current_item %}
            {{ current_item }}
        {% else %}
            Click "Refresh" to start!
        {% endif %}
    </h2>
    <form method="POST">
        <button type="submit">Refresh</button>
    </form>
</body>
</html>

How This Works:

  • Session Persistence: We use Flask's session to store two lists:
    • remaining_items: Starts as a copy of your original list, and we remove items as they're displayed.
    • shown_items: Tracks every item that's already been shown to the user.
  • Button Logic: When the "Refresh" button is clicked, we send a POST request. The server checks if there are leftover items:
    • If yes: Picks a random item, updates the session, and redirects back to show the new item.
    • If no: The template automatically displays the "Finished" message.
  • No Duplicates: Since we remove items from remaining_items after showing them, they can never be selected again until the user's session resets (like closing the browser).

Quick Production Note:

Replace 'your-secure-random-secret-key' with a truly random string (you can generate one with secrets.token_hex(16) in Python) to keep session data secure.

内容的提问来源于stack exchange,提问作者Ed the Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:11:45