feat: Script deletion of old notifications (startinblox/applications/sib-app#228)

This commit is contained in:
Christophe Henry
2019-10-16 18:12:01 +02:00
parent f278f759fb
commit 0529397a88
3 changed files with 102 additions and 2 deletions

View File

@ -1,5 +1,6 @@
import factory
from django.conf import settings
from django.apps import apps
from .models import Notification
from django.db.models.signals import post_save
@ -12,7 +13,7 @@ class NotificationFactory(factory.django.DjangoModelFactory):
type = factory.Faker('text', max_nb_chars=50)
summary = factory.Faker('paragraph', nb_sentences=3, variable_nb_sentences=True)
author = factory.Faker('url')
user = factory.Iterator(settings.AUTH_USER_MODEL.objects.all())
user = factory.Iterator(apps.get_model(settings.AUTH_USER_MODEL).objects.all())
date = factory.Faker('past_datetime')
unread = factory.Faker('boolean')
object = factory.Faker('url')

View File

@ -0,0 +1,52 @@
from textwrap import dedent
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand, CommandError
from djangoldp_notification.models import Notification
def _compute_time_limit(timeout):
"""
>>> _compute_time_limit('10')
10
>>> _compute_time_limit('10h')
600
>>> _compute_time_limit('10m')
10
>>> _compute_time_limit('10d')
14400
"""
try:
if timeout.endswith("d"):
return int(timeout[:-1]) * 24 * 60
elif timeout.endswith("h"):
return int(timeout[:-1]) * 60
elif timeout.endswith("m"):
return int(timeout[:-1])
else:
return int(timeout)
except ValueError:
raise CommandError("--older option is not correct")
class Command(BaseCommand):
help = "Suppress notifications older than 72h"
def add_arguments(self, parser):
parser.add_argument(
"--older",
action="store",
default="72h",
help=dedent(
"""
Set a different time period for notifications to be deleted. Default is 72h
This parameters takes a interger value in minutes by default. 'd', 'h' and 'm' suffix also work.
Examples: --older 10d, --older 10
"""
),
)
def handle(self, *args, **options):
older_than = _compute_time_limit(options["older"])
limit = datetime.today() - timedelta(minutes=older_than)
Notification.objects.filter(date__lte=limit).delete()