Skip to content

Python SDK

The 9n9s Python package provides a simple way to integrate Heartbeat Monitoring into your Python applications and scripts.

Terminal window
pip install 9n9s

First, initialize a client with your Heartbeat Monitor’s UUID. It’s best practice to store this in an environment variable.

import os
from nines import Nines
nines = Nines(os.getenv("MY_JOB_MONITOR_ID"))

To send a simple success pulse:

nines.pulse()

The SDK methods are synchronous by default and run in a background thread so they don’t block your application.

The easiest way to track the execution time of a function is with the @nines.time decorator. It will automatically send a /start pulse before your function runs, and a completion pulse when it finishes. If your function raises an exception, it will automatically send a /fail pulse with the traceback.

@nines.time
def my_important_job():
# ... your job logic ...
print("Doing work!")
my_important_job()

For more control, you can use a context manager.

with nines.time():
# ... your job logic ...
# An exception raised here will be caught and reported
print("Doing more work!")

You can send logs, error details, or any other string payload with your pulses.

# Send a simple log message
nines.pulse(payload='Processed 100 items.')
# Send an exception on failure
try:
1 / 0
except Exception as e:
# The SDK will automatically format the exception and traceback
nines.fail(payload=e)

The SDK is great for monitoring Celery tasks.

from celery import Celery
from nines import Nines
import os
app = Celery('tasks', broker='pyamqp://guest@localhost//')
nines = Nines(os.getenv("CELERY_TASK_MONITOR_ID"))
@app.task
@nines.time
def process_data(x, y):
return x + y

With this setup, every execution of the process_data task will be timed and monitored by 9n9s.