如何在Flask中选择按钮后正确触发random.choice()?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Flask中选择按钮后正确触发random.choice()?相关的知识,希望对你有一定的参考价值。

我是一名Python初学者,我试图建立一个只有一个按钮的网站,每次单击该按钮时,都会弹出一个带有随机Flash游戏的新窗口。

现在,我的按钮正在工作,但是它始终会打开相同的Flash游戏,并且仅当我刷新页面并再次单击时,它会加载新游戏。

有人可以向我解释出什么问题了,我该如何解决? :)

在此之前,我刮了一篇文章,其中包含大约150个指向Flash游戏的链接,这些链接现在都位于.txt文件中,例如:

http://www.tapeonline.com/snowball/

http://www.gamesforwork.com/games/play-4626-Necrathalon-Flash_Game

http://www.adobe.com/macromedia/holiday2004/

http://www.kongregate.com/games/arawkins/dolphin-olympics-2

这是我的代码:烧瓶

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

app = Flask(__name__)


@app.route("/" , methods=['POST','GET'])
def home():
    if request.method == 'POST':
        return redirect("/")
    else: 
        a = open('gamelinks.txt','r')
        b = a.read().split()
        a.close()
        return render_template('index.html', game=random.choice(b))


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

html:

% extends "base.html" %
%block head %

% endblock %
<title>FLASHER</title>
% block body %


<form action = ' game ' method='POST' target="_blank">
    <input type='submit', name='submit', id='submit', value='Play Game'>
</form>


% endblock %
答案

问题是它只能随机选择一次。当您加载页面时,随机值会分配给游戏变量,并一直保持这种状态,直到刷新页面为止。提交表单后,您可能希望使用JS刷新页面:https://www.w3schools.com/jsref/event_onclick.asp

以上是关于如何在Flask中选择按钮后正确触发random.choice()?的主要内容,如果未能解决你的问题,请参考以下文章

展开后执行segue

如何触发 UISearchBar 中的取消按钮?

深入浅出Flask(18): H-ui前端框架的文件上传按钮

如何在UnChecked时触发单选按钮的OnChange事件

UGUI按钮事件获取触发按钮自身组件

如何选择“.on show.bs.modal”内的触发按钮[Bootstrap modal]