[Python] Flask : Storing , Get and Update List in session using flask_session

Discussão em 'Python' iniciado por Stack, Fevereiro 4, 2025.

  1. Stack

    Stack Membro Participativo

    I have been trying for a couple of days, but I have had no success using a session to store the list( e.g., list of notes).

    Below is the code that I have written. It store 2 variables successfully and when I try adding the third variable to the list , it overrides the second variable instead of appending to the list

    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 %}


    Please suggest if there is any way to store, get and update the list variable stored in the session object.

    I have tried using session.modification=True also, which was based on some suggestions on stackoverflow.

    Continue reading...

Compartilhe esta Página