~homeworkprod/byceps

ref: 4237b3ec9496efe95dcce82bea3207ab9de4d520 byceps/scripts/delete_old_user_login_events.py -rwxr-xr-x 1.8 KiB
4237b3ec — Jochen Kupperschmidt Move ticketing blueprint into `site` subpackage 1 year, 10 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python

"""Delete login user events older than a given number of days.

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from datetime import datetime, timedelta

import click

from byceps.database import db
from byceps.services.user.models.event import UserEvent as DbUserEvent
from byceps.util.system import get_config_filename_from_env_or_exit

from _util import app_context


@click.command()
@click.option(
    '--dry-run', is_flag=True, help='count but do not delete affected records',
)
@click.argument('minimum_age_in_days', type=int)
def execute(dry_run, minimum_age_in_days):
    latest_occurred_at = get_latest_occurred_at(minimum_age_in_days)

    click.secho(
        f'Deleting all user login events older than {minimum_age_in_days} days '
        f'(i.e. before {latest_occurred_at:%Y-%m-%d %H:%M:%S}) ...'
    )

    num_deleted = delete_user_login_events_before(latest_occurred_at, dry_run)

    click.secho(f'{num_deleted} user login events deleted.')

    if dry_run:
        click.secho(
            f'This was a dry run; no records have been deleted.', fg='yellow'
        )


def get_latest_occurred_at(minimum_age_in_days: int) -> datetime:
    now = datetime.utcnow()
    return now - timedelta(days=minimum_age_in_days)


def delete_user_login_events_before(
    latest_occurred_at: datetime, dry_run: bool
) -> int:
    num_deleted = DbUserEvent.query \
        .filter_by(event_type='user-logged-in') \
        .filter(DbUserEvent.occurred_at <= latest_occurred_at) \
        .delete()

    if not dry_run:
        db.session.commit()

    return num_deleted


if __name__ == '__main__':
    config_filename = get_config_filename_from_env_or_exit()
    with app_context(config_filename):
        execute()