【问题标题】:Flask : Storing , Get and Update List in session using flask_sessionFlask:使用flask_session在会话中存储、获取和更新列表
【发布时间】:2020-04-24 19:25:58
【问题描述】:

我已经尝试了几天,但我没有成功使用会话来存储列表(例如,笔记列表)。

下面是我写的代码。它成功存储了 2 个变量,当我尝试将第三个变量添加到列表时,它会覆盖第二个变量而不是附加到列表中

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

app = Flask(__name__)

app.config['SECRET_KEY'] = "some_random"
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_PERMANENT']= False

Session(app)

@app.route("/notes", methods=["GET","POST"])
def addNotes():
    if 'notes' not in session:
        session['notes'] = []
    if request.method == "POST":
        note=request.form.get("note")
        notes_list = session['notes']
        notes_list.append(note)
        session['notes'] = notes_list
 
    
    return render_template("notes.html", notes=session['notes'])

notes.html:

{% extends "layout.html" %}

{% block heading %}
    Sticky Notes
{% endblock %}

{% block body %}
    
    <ul>
        {% for note in notes %}
            <li>{{ note }}</li>
        {% endfor %}
    </ul>

    <form action="{{ url_for('addNotes') }}" method="POST">
        <input type="text" name="note" placeholder="Enter a note here">
        <button>Add Note</button>
    </form>
{% endblock %}

请建议是否有任何方法可以存储、获取和更新存储在会话对象中的列表变量。

我也尝试过使用 session.modification=True,这是基于 stackoverflow 上的一些建议。

【问题讨论】:

    标签: python python-3.x flask flask-session


    【解决方案1】:
    @app.route("/notes", methods=["GET","POST"])
    def addNotes():
        if request.method == "POST":
            note = request.form.get("note")
            if 'notes' in session:
                session['notes'] = session['notes'].extend([note])
            else:
                session['notes'] = [note]
    

    这对我有用。但我主要使用会话来存储字典列表。

    由于您将笔记存储在会话中,因此您不必在渲染模板中传递它。在 Jinja 中可以直接访问 session 对象

    <ul>
        {% if session['notes'] %}
        {% for note in session['notes'] %}
            <li>{{ note }}</li>
        {% endfor %}
        {% endif %}
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2017-01-10
      • 2016-09-01
      • 2019-03-11
      • 2014-09-13
      相关资源
      最近更新 更多