Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

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

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.

Upvotes: 1

Views: 9059

Answers (1)

Aneesh Melkot
Aneesh Melkot

Reputation: 1

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

This works for me. But I mostly use sessions to store list of dicts.

Since you are storing your notes in the session, you don't have to pass it in the render template. You can directly access the session object in Jinja

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

Upvotes: 0

Related Questions