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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With