在 Flask 中,每当我重新加载页面时,列表的最后一条注释都会再次添加一次,这是我不想要的



这是我的烧瓶代码:

from flask import Flask, render_template, request, session  
from flask_session import Session

app=Flask(__name__)
app.config["SESSION_PERMANENT"]=False
app.config["SESSION_TYPE"]="filesystem"
Session(app)
@app.route("/", methods=["GET","POST"])    
def index():
if session.get("notes") is None:
session["notes"]=[]
if request.method=="POST":
note=request.form.get("note")
session["notes"].append(note)
return render_template("index1.html", notes=session["notes"])

问题:

例如,如果我写hello并添加note,它会被添加,但当我重新加载页面时,hello会被单独添加一次。

我认为这是由我个人不知道的flask会话模块引起的,但我可以通过添加带有重定向的url_fo来修复它。

from flask import Flask, render_template, request, session, redirect, url_for
from flask_session import Session

app=Flask(__name__)
app.config["SESSION_PERMANENT"]=False
app.config["SESSION_TYPE"]="filesystem"
Session(app)
@app.route("/", methods=["GET","POST"])    
def index():

if session.get("notes") is None:
session["notes"]=[]
if request.method=="POST":

note=request.form.get("note")
session["notes"].append(note)
return redirect(url_for('index'))
return render_template("index.html", notes=session["notes"])
if __name__ == '__main__':
app.run(debug=True)

我想明白了,伙计们:只需添加if-else语句:

if note in session["notes"]:
pass
else:
session["notes"].append(note)

最新更新