#2 Counting Number of Visits to Website

302 views - Pratyush Singh
Tag(s) : webdev django backend Dec. 7, 2016, 11:25 p.m.
A workaround to get number of visits to your website

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
    # 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

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

Here datetime and timedelta are imported from datetime. In this way, if a user comes to your website and visits many pages in a row, the visit count won't increase. But if he comes for the first time, or after an interval of 15 minutes, we will have the visitor count increased by 1.

This was how I figured it out. If you have any suggestions or queries, please feel free to mail me.

Update 1 - Crawl Bots

This method also takes into account the robots that visit your website. Clearly, this will not lead to a good estimate. To overcome this, we can simply ignore the User agents before incrementing the visit counter. DeviceAtlas' post provides a list of popular user agents for crawl bots.