-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelete_cohorts_with_prefix.py
More file actions
73 lines (57 loc) · 1.83 KB
/
delete_cohorts_with_prefix.py
File metadata and controls
73 lines (57 loc) · 1.83 KB
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
66
67
68
69
70
71
72
73
"""
Deletes all cohorts that start with a given prefix.
The prefix should be something like "2324_".
We need this script because there is no bulk cohort delete in the moodle admin interface
Uses the Moodle API
"""
import argparse
import os
import sys
import dotenv
import structlog
from lib.moodle_api import URL, MoodleClient
log = structlog.get_logger()
BATCH_SIZE = 500
def delete_moodle_cohorts_with_prefix(moodle: MoodleClient, prefix: str):
result = moodle(
"core_cohort_search_cohorts",
query=prefix,
context={
"contextid": 1
}, # 1 is the system context (even though some docs say that is 10)
limitfrom=0,
limitnum=BATCH_SIZE,
)
cohorts_to_delete = result.cohorts
if not cohorts_to_delete:
print("No cohorts found, nothing to do")
return
for i, cohort in enumerate(cohorts_to_delete):
log.info(
"cohort",
index=i,
name=cohort.name,
)
print()
user_input = input(
f"Do you want to delete these {len(cohorts_to_delete)} cohorts (yes/no): "
)
if user_input.lower() != "yes":
print("Aborting")
sys.exit(0)
cohort_ids_to_delete = [cohort.id for cohort in cohorts_to_delete]
moodle("core_cohort_delete_cohorts", cohortids=cohort_ids_to_delete)
log.info("Done")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=f"Deletes {BATCH_SIZE} moodle cohorts that start with a prefix"
)
parser.add_argument("prefix")
args = parser.parse_args()
dotenv.load_dotenv()
token = os.getenv("TOKEN")
if not token:
sys.exit("Missing environment variable 'TOKEN'")
log.info("connecting", url=URL, token=token)
moodle = MoodleClient(URL, token)
delete_moodle_cohorts_with_prefix(moodle, args.prefix)