Answer the question
In order to leave comments, you need to log in
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
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) #Страницы для отслеживания
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()
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')
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()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question