Django - unique online visitors counter

August 16, 2012 - IT

I like watching usage statistics of my applications ;-) I have decided to show number of online users. Intranet. Access for logged anonymous and anonymous users. Simply code. I have been checking unique IP addresses. Everything is stored in memcached.

Add django.core.contextprocessors.request to TEMPLATECONTEXT_PROCESSORS.

from django.conf import global_settings

Add OnlineNowMiddleware to MIDDLEWARE_CLASSES.


Main OnlineNowMiddleware code.

from django.core.cache import cache

class OnlineNowMiddleware(object):

    def process_request(self, request):
        # Check the IP address
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            user_ip = x_forwarded_for.split(',')[0]
            user_ip = request.META.get('REMOTE_ADDR')
        # Get the list of the latest online users
        online = cache.get('online_now')
        # Check the active IP addresses
        if online:
            online = [ip for ip in online if cache.get(ip)]
            online = []
        # Add the new IP to cache
        cache.set(user_ip, user_ip, 600)
        # Add the new IP to list if doesn't exist
        if user_ip not in online:
        # Set the new online list
        cache.set('online_now', online)
        # Add the number of online users to request
        request.__class__.online_now = len(online)

Finally, show the number of online users.

{{ request.online_now }}