首页 > 解决方案 > 当会话对象是列表时如何修改烧瓶会话对象

问题描述

我有一个 Session 对象作为列表,我想在列表中更新它。我试图迭代 Flask Session 对象并且它有效,但是当我尝试修改 Flask Session 中的值时,它给了我一个错误。

@app.route("/")
def index():
    if "lenta" not in session:
        session["lenta"] = [[None, None, None], [None, None, None], [None, None, None]]
        session["move"] = "X"

    return render_template("game.html", game=session["lenta"], move=session["move"])


@app.route("/play/<int:row>/<int:col>")
def play(row, col):
    for i in session["lenta"]:
        for j in i:
            session["lenta"][i][j] = row, col
            redirect(url_for("index"))

我希望session["lenta"][i][j]它将使用 HTML 中的值 Row 和 Col 进行更新,但我收到错误消息:

session["lenta"][i][j] = row, col
TypeError: list indices must be integers or slices, not list

标签: pythonsessionflask

解决方案


看起来您正在迭代session['lenta'](ie for i in session["lenta"]) 的元素,但 session["lenta"] 的元素本身就是列表(例如[None, None, None])。这就是您收到此错误的原因。

要解决它,请尝试调用您正在迭代的元素,如下所示:

def play(row, col):
    for el in session["lenta"]:
        for j, _ in enumerate(el):
            el[j] = row, col
            redirect(url_for("index"))

看看这是否有效,祝你好运!

[为澄清而编辑]:我没有你的全部代码,我检查过的是:

z = [[None, None, None], [None, None, None], [None, None, None]]
for vi in z:
    for j,vj in enumerate(z):
        vi[j] = (i,j)

(在 Python 3.6 上)


推荐阅读