Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django set session variable till end of day

I need to set a session variable that expires at the end of each day.

I know I can set a session variable like this:

request.session['my_variable'] = 'foo'

How can I then have this expire at the end of the day?

like image 433
Atma Avatar asked Sep 17 '25 18:09

Atma


1 Answers

In most cases, you don't want to expire the whole session. So there is a way to expire only the one variable - save the variable in the dictionary with the expiration time.

def set_expirable_var(session, var_name, value, expire_at):
    session[var_name] = {'value': value, 'expire_at': expire_at.timestamp()}

Set the variable using this function:

expire_at = datetime.datetime.combine(datetime.date.today(), datetime.datetime.max.time())
set_expirable_var(request.session, expire_at)     

And before you get the value you should check whether the variable is not expired.

def get_expirable_var(session, var_name, default=None):
    var = default
    if var_name in session:  
        my_variable_dict = session.get(var_name, {})
        if my_variable_dict.get('expire_at', 0) > datetime.datetime.now().timestamp():
            myvar = my_variable_dict.get('value')
    else:
        del session[var_name]
    return var
like image 156
Vadim Serdiuk Avatar answered Sep 20 '25 08:09

Vadim Serdiuk