Python SDK
The 9n9s Python package provides a simple way to integrate Heartbeat Monitoring into your Python applications and scripts.
Installation
Section titled “Installation”pip install 9n9sInitializing the Client
Section titled “Initializing the Client”First, initialize a client with your Heartbeat Monitor’s UUID. It’s best practice to store this in an environment variable.
import osfrom nines import Nines
nines = Nines(os.getenv("MY_JOB_MONITOR_ID"))Signaling Success
Section titled “Signaling Success”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.
Tracking Runtimes with Decorators
Section titled “Tracking Runtimes with Decorators”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.timedef my_important_job(): # ... your job logic ... print("Doing work!")
my_important_job()Tracking Runtimes with Context Managers
Section titled “Tracking Runtimes with Context Managers”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!")Sending Payloads
Section titled “Sending Payloads”You can send logs, error details, or any other string payload with your pulses.
# Send a simple log messagenines.pulse(payload='Processed 100 items.')
# Send an exception on failuretry: 1 / 0except Exception as e: # The SDK will automatically format the exception and traceback nines.fail(payload=e)Use with Celery
Section titled “Use with Celery”The SDK is great for monitoring Celery tasks.
from celery import Celeryfrom nines import Ninesimport os
app = Celery('tasks', broker='pyamqp://guest@localhost//')nines = Nines(os.getenv("CELERY_TASK_MONITOR_ID"))
@app.task@nines.timedef process_data(x, y): return x + yWith this setup, every execution of the process_data task will be timed and monitored by 9n9s.