Django Pgactivity

1.8.0 · active · verified Sat Apr 11

django-pgactivity is a Python library that provides tools to monitor, kill, and analyze active PostgreSQL queries directly from a Django application. It offers a proxy model for the `pg_stat_activity` view, a management command, and utilities like query context annotation and dynamic statement timeouts. The current version is 1.8.0, and it maintains an active release cadence, frequently updating to support new versions of Python, Django, and PostgreSQL.

Warnings

Install

Imports

Quickstart

To get started, add 'pgactivity' to your Django project's `INSTALLED_APPS`. You can then use the `pgactivity` management command to view and filter active PostgreSQL queries, or integrate its features programmatically. The example demonstrates using the `@pgactivity.timeout` decorator to enforce a statement timeout on a view function. Make sure your Django project is correctly configured to use PostgreSQL as its database backend.

# settings.py
INSTALLED_APPS = [
    # ...
    'pgactivity',
    # ...
]

# myapp/views.py (example using timeout decorator)
import pgactivity
from django.db import connection, utils
from django.http import HttpResponse

@pgactivity.timeout(0.5) # Set a 500ms timeout for queries in this view
def my_slow_view(request):
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT pg_sleep(1)") # This will likely time out
        return HttpResponse("Operation completed within timeout.")
    except utils.OperationalError as e:
        return HttpResponse(f"Operation timed out or failed: {e}", status=500)

# To view active queries from the command line:
# python manage.py pgactivity

view raw JSON →