Monitoring Scripts
A monitoring script is something that you want to execute recurrently withing the breathecode API, for example:
scripts/alert_pending_leads.py
is a small python script that checks if there is FormEntry Marketing module database that are pending processing.
You can create a monitoring script to remind academy staff members about things, or to remind students about pending homework, etc.
Stepts to create a new script:
- create a new python file inside
./breathecode/monitoring/scripts
- make sure your script starts with this content always:
#!/usr/bin/env python
"""
Alert when there are Form Entries with status = PENDING
"""
from breathecode.utils import ScriptNotification
# start your code here
- You have access to the entire breathecode API from here, you can import models, services or any other class or variable from any file.
- You can raise a
ScriptNotification
to notify forMINOR
orCRITICAL
reasons, for example:
# here we are raising a notification because there are 2 pending tasks
raise ScriptNotification("There are 2 pending taks", status='MINOR', slug="pending_tasks")
Global Context
There are some global variables that you have available during your scripts:
Variable name | Value |
---|---|
academy | Contains the academy model object, you can use it to retrieve the current academy id like this: query.filter(academy__id=academy.id) |
Manually running your script
You can test your scripts by running the following command:
$ python manage.py run_script <file_name>
# For example you can test the alert_pending_leads script like this:
$ python manage.py run_script alert_pending_leads.py
Example Script
The following script checks for pending leads to process:
#!/usr/bin/env python
"""
Alert when there are Form Entries with status = PENDING
"""
from breathecode.marketing.models import FormEntry
from django.db.models import Q
from breathecode.utils import ScriptNotification
# check the database for pending leads
pending_leads = FormEntry.objects.filter(storage_status="PENDING").filter(Q(academy__id=academy.id) | Q(location=academy.slug))
# trigger notification because pending leads were found
if len(pending_leads) > 0:
raise ScriptNotification(f"Warning there are {len(pending_leads)} pending form entries", status='MINOR')
# You can print this and it will show on the script results
print("No pending leads")
Unit testing your script
from breathecode.monitoring.actions import run_script
script = run_script(model.monitor_script)
del script['slack_payload']
del script['title']
expected = {'details': script['details'],
'severity_level': 5,
'status': script['status'],
'text': script['text']
}
self.assertEqual(script, expected)
self.assertEqual(self.all_monitor_script_dict(), [{
**self.model_to_dict(model, 'monitor_script'),
}])