<commit_before>"""
The django clearsessions commend internally calls:
   cls.get_model_class().objects.filter(
       expire_date__lt=timezone.now()).delete()
which could lock the DB table for a long time when
having a large number of records to delete.

To prevent the job running forever, we only delete a limit number of
expired django sessions in a single run
"""

import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sessions.models import Session
from django.utils import timezone
from myuw.logger.timer import Timer

logger = logging.getLogger(__name__)
DEL_SIZE = 10000


class Command(BaseCommand):

    def handle(self, *args, **options):
        limit = self.get_limit()
        try:
            timer = Timer()
            qs = Session.objects.filter(
                expire_date__lt=timezone.now())[0:limit]
            if qs.exists():
                qs.delete()
            logger.info(
                "clear_expired_sessions, Time={} seconds".format(
                    timer.get_elapsed()))
        except Exception as ex:
            logger.error(str(ex))

    def get_limit(self):
        num = getattr(settings, 'DEL_SESSION_NUM', None)
        return int(num) if num else DEL_SIZE<commit_msg>Resolve MUWM-4639<commit_after>"""
The django clearsessions commend internally calls:
   cls.get_model_class().objects.filter(
       expire_date__lt=timezone.now()).delete()
which could lock the DB table for a long time when
having a large number of records to delete.

To prevent the job running forever, we only delete a limit number of
expired django sessions in a single run
"""

import logging
from datetime import timedelta
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sessions.models import Session
from django.utils import timezone
from myuw.logger.timer import Timer

logger = logging.getLogger(__name__)
begin_delta = 1920
log_format = "Deleted django sessions expired before {}, Time={} seconds"


class Command(BaseCommand):

    def handle(self, *args, **options):
        now = timezone.now()
        for ddelta in range(begin_delta, 0, -1):
            timer = Timer()
            cut_off_dt = now - timedelta(days=ddelta)
            try:
                qset = Session.objects.filter(expire_date__lt=cut_off_dt)
                if qset.exists():
                    qset.delete()
                    logger.info(log_format.format(cut_off_dt.date(),
                                                  timer.get_elapsed()))

            except Exception as ex:
                logger.error(str(ex))
{'fraction_non_alphanumeric': 0.08528301886792453, 'fraction_numerical': 0.0060377358490566035, 'mean_word_length': 2.6922005571030643, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2396685', 'n_tokens_mistral': 743, 'n_tokens_neox': 698, 'n_words': 229}