Tuesday, 2 November 2021

Integrating Flask/Dill to dump/load server sessions

I'm trying to integrate Flask with Dill to dump/load Python sessions on the server side. The code below has two functions, the first one sets the value of x to zero and imports the datetime library. The second one increments x by 1 and gets the timestamp.

The first function dumps the session and the second function loads it.

In the dump, the pickle file is generated correctly, but I cannot reuse x or get the timestamp.

This is the error when I try to execute x = x + 1 in the second function:

UnboundLocalError: local variable 'x' referenced before assignment

Can Dill be used with Flask? Do I need a different approach?

The code:

from flask import Flask
from dill import dump_session, load_session

app = Flask(__name__)
app.config['SECRET_KEY'] = 'super secret'

session_file = '/tmp/session.pkl'

@app.route('/start_counter')
def start_counter():
    import datetime
    x = 0
    dump_session(filename = session_file)
    return 'New counter started!'

@app.route('/count')
def count():
    load_session(filename = session_file)
    x = x + 1
    now = datetime.datetime.now()
    dump_session(filename = session_file)
    return str(x) + '-' + str(now)


from Integrating Flask/Dill to dump/load server sessions

No comments:

Post a Comment