Skip to content

Commit

Permalink
Add clean_observers management commands
Browse files Browse the repository at this point in the history
that cleans old subscriptions
  • Loading branch information
gregorjerse committed Sep 11, 2023
1 parent 3b638ce commit 9188a3e
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 0 deletions.
4 changes: 4 additions & 0 deletions docs/CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ Changed
- Relation slug can be updated
- Anonymous user can access the annotation field endpoint

Added
-----
- Add ``clean_observers`` management command to clean old subsciptions


===================
36.0.0 - 2023-07-17
Expand Down
10 changes: 10 additions & 0 deletions resolwe/observers/management/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
""".. Ignore pydocstyle D400.
====================
Observers Management
====================
.. automodule:: resolwe.observers.management.commands.register
:members:
"""
1 change: 1 addition & 0 deletions resolwe/observers/management/commands/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Management commands module."""
54 changes: 54 additions & 0 deletions resolwe/observers/management/commands/clean_observers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
""".. Ignore pydocstyle D400.
=======================
Clean old observer data
=======================
Command to run:
./manage.py clean_observers
"""
import logging

from django.core.management.base import BaseCommand
from django.utils import timezone

from resolwe.observers.models import Observer, Subscription

# Delete subscriptions older than DELETE_OLDER_THAN hours.
DELETE_OLDER_THAN = 5 * 24

logger = logging.getLogger(__name__)


class Command(BaseCommand):
"""Delete old observers subscriptions."""

help = "Delete old observer subscriptions."

def add_arguments(self, parser):
"""Command arguments."""
parser.add_argument(
"--older-than",
type=int,
dest="older_than",
help="Delete subscriptions older than older-than hours",
)

def handle(self, *args, **options):
"""Delete old observer subscriptions."""
delete_older_than = options["older_than"] or DELETE_OLDER_THAN
logger.info(
"Deleting observer subscriptions older than %d hours.", delete_older_than
)
# Delete subscriptions older than delete_older_than hours.
deleted_subscriptions = Subscription.objects.filter(
created__lt=timezone.now() - timezone.timedelta(hours=delete_older_than)
).delete()[0]
logger.info("Deleted %d subscriptions.", deleted_subscriptions)
# Delete observers without subscriptions.
deleted_observers = Observer.objects.filter(
subscriptions__isnull=True
).delete()[0]
logger.info("Deleted %d observers.", deleted_observers)

0 comments on commit 9188a3e

Please sign in to comment.