We all have seen those websites where number of views increases as we refresh the page. But do you actually get impresses by looking at the huge number it displays? Maybe not that much as you know that many of these visits are redundant. In this post, I will discuss about how can you get better numbers for number of visits.
We set up a cookie that stores the time upto which we will not consider the visit of browser as a new visit. And we increment the count only if the user comes without such cookie or comes with an expired one.
curr_time = datetime.now() next_time = now + timedelta(minutes=15) # Next value of cookie time_cookie = request.COOKIES.get('time_cookie', None) if not time_cookie: # Cookie wasn't set, new session increment_visits() else: # Convert it to datetime for comparison time_cookie_val = datetime.strptime(time_cookie, '%Y-%m-%d %H:%M:%S.%f') if time_cookie_val < curr_time: # User came back after 15 minutes increment_visits() context['visit_count'] = get_visits() response = render(request, 'mypage.html', context) # Render response # Set time_cookie to next expiry response.set_cookie(key='time_cookie', val=str(next_time)) return response
This was how I figured it out. If you have any suggestions or queries, please feel free to mail me.