Home > Back-end >  User activity concept using django
User activity concept using django

Time:08-10

I need to make a feature which shows if user is active or not (like on facebook). What is the best and most common way to do this? My concept looks like this:

When the user logs in or refreshes the JWT token, it starts a javascript loop which sends f.e. every 3 minutes post request which sets inside User model object current date. Then if another user will enter that user's profile he will get the date from User object and check if current date minus the date from User object < 3 min - if so, it means that user is active, else user is not active.

Is it a good way? Should I use websockets for it? I am using DRF and React.

CodePudding user response:

My preferred way of tracking user activity is with some custom middleware. The main problem i have with javascript loops is that if a user leaves their browser open then they could be mistakenly identified as being active on your site. Tracking last active with middleware requires a request to be made by the user, which guarantees they are indeed active. I've included an example below for you to follow:

# custom_middleware.py

class LastActiveMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Update last activity
        user = request.user
        if user.is_authenticated:
            last_active = user.last_active
            now = timezone.now()
            if last_active <= now - datetime.timedelta(minutes=3):
                user.last_active = now
                user.save()

        response = self.get_response(request)

        return response

And then add your custom middleware to MIDDLEWARE in settings:

# settings.py

MIDDLEWARE = [
    ...
    custom_middleware.LastActiveMiddleware
]
  • Related