meteor
meteor

Reputation: 658

Update cookie in django without resetting expiration time

Is it possible to update cookie value, without resetting it, i need to save expiration time? Currently i try to do something like that:

class SetBannerCookie(object):
    def process_template_response(self, request, response):
        max_age = 60
        banners = Banner.objects.filter(active=True, show_start_date__lte=timezone.now(), show_end_date__gte=timezone.now())

        for banner in banners:
            cookie_name = 'banner_'+str(banner.id)
            if cookie_name in request.COOKIES:
                # update value only here
            else:
                response.set_cookie(cookie_name, value='yes', max_age=max_age, path='/')
        return response

Upvotes: 2

Views: 637

Answers (1)

masnun
masnun

Reputation: 11906

You can get the expiration of a cookie and then update the cookie with new value while setting the remaining expiration time as the expiry.

For example we set a cookie with 60mins expiry time left. After 20 mins, it has 40 mins left. Now we can update the coookie and set expiry to be 40 mins. Thus we can keep the original expiration.

request.META['HTTP_COOKIE'] would contain the original cookie string. We can use SimpleCookie class to decode the values. Now do the calculation and update it.

Upvotes: 3

Related Questions