librelist archives

« back to archive

Problem with session variable

Problem with session variable

Roberto Pinto
2015-07-13 @ 09:35
Hello, I am a Flask beginner and I am experiencing problems using session
variables. I programmed in PHP for a while and session variables were
really easy. In Python-Flask I think I am missing something. Here is my

1) when a user logs in I set a session variable
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        session['info_released'] = 0
        app.logger.debug('info_released session value:

The logs confirms the value of the session variable.

2) in another view function called via an ajax request, I check the value
of the session variable and, if needed, change it.

   @app.route('/get_actual_demand', methods=['GET', 'POST'])
    def get_actual_demand():'> SESSION: {}'.format(session['info_released']))

        if request.json['counter'] == 10 and session['info_released'] == 0:
            session['info_released'] = 1
            return jsonify(released=1)
            return jsonify(released=0)

The counter variable passed to the function is incremented periodically by
another function. When the counter is equal to 10, and before it is
incremented to 11, the function get_actual_demand is called several times
via ajax. I want to execute the #code_to_be_executed_once just the first
Checking the log, the session['info_released'] is changed to 1 when
request.json['counter'] == 10, but in the next call the value is set back
to 0: indeed, the #code_to_be_executed_once is run many times until the
counter gets incremented.

3) I also tried in another way. I removed the session['info_released'] = 0
from the login() view function and changed the get_actual_demand() as

    @app.route('/get_actual_demand', methods=['GET', 'POST'])
    def get_actual_demand_modified():
        # the variable session['info_released'] is no more
        # defined in the login() function

        if request.json['counter'] == 10:
                # The first time I get here, raise a KeyError exception
                if session['info_released'] == 1:
                    return jsonify(released=0)
            except KeyError:
                # Use `session['info_released']` as a flag,
                # defined here
                session['info_released'] = 1
                return jsonify(released=1)
            return jsonify(released=0)

But then again, checking the log (removed from the code) I can see the
session variable defined when it first hits the exception, but then the
program hits again the exception as if the session variable is still not
So, I think I missing something basic here but I don't understand what.
I am serving the app locally on my laptop using gunicorn.
Thanks in advance.