Y
Y
YraganTron2016-11-30 04:55:40
Django
YraganTron, 2016-11-30 04:55:40

Working with sessions in django. How to track the number of users per page per hour and the number of active users per page per 24 hours?

Good day. The problem is described in the question. Suppose I have 2 pages and I need to track all this on them, initially there was an idea to do something like this.
request.session['моя страница'] = True
But all my sessions are stored in the database as a cache, so I will have to decode each entry in order to get a dictionary, track the value and calculate. It's kind of like a lot of code and inefficient. Even at the level of the idea, I do not understand how to implement it correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
YraganTron, 2016-12-09
@YraganTron

Understood the question, maybe it will be useful to someone. Django saves session data by default (only if you change something in the session) in the Session model.
I made table MySession

class MySession(models.Model):
    session_key = models.ForeignKey(Session) # Связь с таблицой Session
    name_board = models.CharField(max_length=1024) #Страницы для отслеживания
    expire_date = models.DateTimeField() # Время жизни
    active = models.CharField(max_length=1024, blank=True) #Отслеживание действий на странице
    thread = models.TextField(blank=True) #Страницы для отслеживания

After that, in the view, I describe the work with sessions and Mysession.
request.session.set_expiry(3600) #Задаю нужное мне время жизни сессии
    request.session.save()

    if len(MySession.objects.filter(session_key=request.session.session_key)) != 0:  # Проверяю, есть ли информация о данной сессии в Mysession, и есть ли информация о посещении данной страницы. Если информация нет, то добавляю.
        session = MySession.objects.get(session_key=request.session.session_key)
        if name_board in session.name_board:
            pass
        else:
            session.name_board += ', ' + name_board
        session.save()
    else:        MySession.objects.create(session_key=Session.objects.get(pk=request.session.session_key), name_board=name_board, expire_date=Session.objects.get(pk=request.session.session_key).expire_date)
        session = MySession.objects.get(session_key=request.session.session_key)
        session.save()

Next, I create my own django command to remove all sessions whose lifetime has expired and further count the number of remaining sessions. I will count through the signals
usr_hour = Signal(providing_args=[]) # Создание сигнала

class Command(BaseCommand):

    def handle(self, *args, **options):
        now = timezone.now() # Задаю время для проверки жизни сессий
        two_hour = now - datetime.timedelta(hours=2)
        MySession.objects.filter(expire_date__range=(two_hour, now)).delete()
        Session.objects.filter(expire_date__range=(two_hour, now)).delete()

        usr_hour.connect(my_callback) #отправляю сигнал
        usr_hour.send(sender=self.__class__)
        usr_hour.disconnect(my_callback)

        self.stdout.write('Succes')

Signal
def my_callback(sender, **kwargs):
    boards = Board.objects.all()
    for x in boards:
        x.board_in_hour = MySession.objects.filter(name_board__contains=x.board_shortcut).count()
        x.save()

I add the launch of the db_hour command on cron every hour. Thus, you can calculate the number of users for each hour on ODA. pages

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question