~linaro-infrastructure/linaro-license-protection/master

« back to all changes in this revision

Viewing changes to license_protected_downloads/management/commands/token_cleanup.py

  • Committer: Benjamin Copeland
  • Date: 2019-09-26 17:07:56 UTC
  • Revision ID: git-v1:934e8826f5496d584b60fd285093a14d782c92ba
Token_cleanup: Add a token cleanup script

We have a large amount of expired API tokens sitting the database, this
script will run as a crontab and clean them up.

Change-Id: Ibbae225fe45f69956bc40bddcd7d76cf69cd6aff
Reviewed-on: https://review.linaro.org/c/infrastructure/linaro-license-protection/+/32892
Reviewed-by: Riku Voipio <riku.voipio@linaro.org>

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from django.conf import settings
 
2
from django.core.management.base import BaseCommand
 
3
from license_protected_downloads.models import (
 
4
    APIToken,
 
5
    APILog
 
6
)
 
7
import logging
 
8
import datetime
 
9
 
 
10
logging.getLogger().setLevel(logging.INFO)
 
11
 
 
12
 
 
13
class Command(BaseCommand):
 
14
    @staticmethod
 
15
    def add_arguments(parser):
 
16
        parser.add_argument('--dryrun', action='store_true',
 
17
                            help='Do not perform any actions, just report')
 
18
        parser.add_argument('--deletedays', default=30,
 
19
                            help='Number of days to delete files for good')
 
20
 
 
21
    @staticmethod
 
22
    def x_days_ago(days):
 
23
        date = datetime.datetime.now() - datetime.timedelta(days=days)
 
24
        return date.isoformat()
 
25
 
 
26
    def handle(self, *args, **options):
 
27
        now_delete = self.x_days_ago(int(options['deletedays']))
 
28
        keys = APIToken.objects.filter(expires__lte=now_delete).delete()
 
29
 
 
30
        if options['dryrun']:
 
31
            logging.info('DRYRUN: DELETE %s, EXPIRE: %s', key.token, key.expires)
 
32
        else:
 
33
            APIToken.objects.filter(expires__lte=now_delete).delete()
 
34
            APILog.objects.filter(timestamp__lte=now_delete).delete()