如何解决如何清除Flask中现有的Flash消息
我在Flask中有一条警告Flash消息,该消息出现在用户尝试根据有关用户的背景信息提交表单之前。如果用户继续前进并以不被警告的方式提交表单,则会阻止他们并看到第二条刷新消息。我想在用户看到第二条即显信息之前清除第一条即显信息。
我已经阅读了Flash邮件上的Flask文档,并尝试通过Google搜索答案。我还阅读了一些Flask source code。没有解决的办法向我扑过来。
有人可以帮我弄清楚如何清除即显消息吗?
解决方法
这样,您可以清除Flash消息,因为Flask Flash助手中没有预定义的方法可以清除Flash消息。 您可以尝试以下代码。它对我有用,也许对您有用。
session.pop('_flashes',None)
,
虽然Jitendra Kumar解决方案看起来不错,并且实际上回答了更多有关如何清除闪光灯的问题,但我的解决方案是一种替代方法,可能会有所帮助。
我的代码分为3个文件。
Python文件:
从flask导入Flask,render_template,url_for,请求,Flash,重定向 导入操作系统
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(16)
@app.route("/",methods=['GET','POST'])
def home():
if request.method == 'POST':
first= request.form.get('first')
second= request.form.get('second')
if first != None:
flash('Remove this flash')
if second != None:
flash('Another')
return render_template('index.html') #The flash is not cleared but a new one pops up
return render_template('index.html')
if __name__ == "__main__":
app.run(port=8000,debug=True)
宏Html,注意,我正在使用Bootstrap的警报,以便用户可以关闭闪光灯:
{% macro flash()%}
{% for msg in get_flashed_messages()%}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>{{msg}}</strong>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% endmacro %}
HTML表单:
<body>
{% from 'macro.html' import flash%}
<div class="container"> <h1>Flash Trainings</h1></div>
<br><br><br>
<form action="" method="post">
<!-- First Flash -->
<div class="form-group">
<input type="submit" class="btn btn-primary form-control" value="Are you sure?" name="first">
</div>
<br>
<!-- Second Flash -->
<div class="form-group">
<input type="submit" class="btn btn-primary form-control" value="Profile" name="second">
</div>
</form>
<!-- Macro's function -->
{{flash()}}
</body>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。