skip to Main Content

I want to check if a value, for example the ‘name’ value, exists in a session in a Flask application I made, but it’s not working.

Python:



@app.route("/add/<string: name>")

def add(name):

    session["list"].append(name)

    return "Successful"

@app.route("/list

def list():

    cursor=mysql.connection.cursor()

    query="Select * From data where id=1"

    cursor.execute(query)

    data=cursor.fetchone()

    return render_template("list.html",data=data)

HTML:



{% if data.name in session["list"] %}

There is

{% else %}

None

{% endif %}

Even if the data.name value is in the session, it goes into the else block

2

Answers


  1. 1.session is a dict. So if you want the value of a key of this dict to be a list, you should initialise it. (session['list'] = [])

    2.The closing quote is missing in the route of /list(@app.route("/list"))

    3.Make sure to import session and configure the secret_key(probably you would have imported, but not shown in the code)

    4.While fetching from database, if data is dict, you should mention {% if data['name'] in session["list"] %} in your jinja2 code. If data is object, you should mention data.name like {% if data.name in session["list"] %}. Ensure whether it is used properly.

    5.To know if value is inside session, add error handling in the code

    @app.route("/add/<string:name>")
    def add(name):
        try:
            # Initialize session list if not already present
            if "list" not in session:
                session["list"] = []
            
            # Add the name to the session list
            session["list"].append(name)
            return "Successful"
        except Exception as e:
            # Log the error (optional) and provide user feedback
            app.logger.error(f"Error adding name to session: {e}")
            return "An error occurred", 500
    
    Login or Signup to reply.
  2. If you save a list within the session and do not make a new assignment but add an item to the list, it is necessary to mark the session as modified. This applies to all changes to mutable structures.

    @app.route("/add/<string:name>")
    def add(name):
        session["list"].append(name)
        session.modified = True
        return "Successful"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search