Django Pgactivity
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
- breaking Version 1.8.0 dropped support for Python 3.9. Users on Python 3.9 must upgrade their Python version to 3.10 or later before upgrading to django-pgactivity 1.8.0.
- breaking Earlier versions dropped support for older environments: 1.7.0 dropped Python 3.8 support, and 1.5.0 dropped Django 3.2 and Postgres 12 support. Ensure your environment meets the compatibility requirements (Python 3.10+, Django 4.2+, Postgres 14+).
- gotcha Forgetting to add 'pgactivity' to `INSTALLED_APPS` in your Django `settings.py` will result in `AppRegistryNotReady` or `ModuleNotFoundError` errors when trying to use its features like the `PGActivity` model or management commands.
- gotcha Effective use of `django-pgactivity` requires a correctly configured PostgreSQL database in Django's `settings.DATABASES`. Incorrect `ENGINE`, `NAME`, `USER`, `PASSWORD`, `HOST`, or `PORT` will prevent the library from connecting to and monitoring your database.
- gotcha The `pg_stat_activity` view (which `django-pgactivity` queries) provides extensive information about active queries, but it does not directly expose memory usage statistics. For memory monitoring, you would need to use operating-system level facilities or more specialized PostgreSQL monitoring tools.
Install
-
pip install django-pgactivity
Imports
- PGActivity
from pgactivity.models import PGActivity
- pgactivity.context
import pgactivity # then use @pgactivity.context(...) or with pgactivity.context(...)
- pgactivity.timeout
import pgactivity # then use @pgactivity.timeout(...)
- ActivityMiddleware
from pgactivity.middleware import ActivityMiddleware
Quickstart
# 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