API Reference

django_statsd Package

django-statsd: submit Django query and view durations to statsd.

django_statsd.__init__.decorator(prefix)[source]

Return a decorator timing each call under prefix.

Parameters:

prefix (str)

Return type:

Callable[[Callable[[~P], T]], Callable[[~P], T]]

django_statsd.__init__.decr(key, value=1)[source]

Subtract value from the counter key, if a scope is open.

Parameters:
Return type:

None

django_statsd.__init__.incr(key, value=1)[source]

Add value to the counter key, if a scope is open.

Parameters:
Return type:

None

django_statsd.__init__.named_wrapper(name, f)[source]

Wrap f so each call is timed as name.

Parameters:
Return type:

Callable[[~P], T]

django_statsd.__init__.start(key)[source]

Start timing key in the current scope, if there is one.

Parameters:

key (str)

Return type:

None

django_statsd.__init__.stop(key)[source]

Stop timing key.

Returns:

The elapsed seconds, or None outside a tracked request.

Parameters:

key (str)

Return type:

float | None

django_statsd.__init__.with_(key)[source]

Return a context manager timing key.

Returns:

A timer inside a tracked request, and a no-op outside one.

Parameters:

key (str)

Return type:

WithTimer | DummyWith

django_statsd.__init__.wrapper(prefix, f)[source]

Wrap f so each call is timed as <prefix>.<function name>.

Parameters:
Return type:

Callable[[~P], T]

settings Module

Django settings wrappers with safe defaults for django-statsd.

django_statsd.settings.get_setting(key, default=None)[source]

Read key from Django’s settings.

Returns default when Django is not configured yet, so importing this module never raises.

Parameters:
Return type:

Any

django_statsd.settings.STATSD_TRACK_MIDDLEWARE = True

Enable tracking all requests using the middleware

django_statsd.settings.STATSD_PREFIX = 'prefix'

Set the global statsd prefix if needed. Otherwise use the root

django_statsd.settings.STATSD_DEBUG = True

Enable warnings such as timers which are started but not finished. Defaults to DEBUG if not configured

django_statsd.settings.STATSD_DISABLED = False

Statsd disabled mode, avoids sending metrics to the real server. Useful for debugging purposes.

django_statsd.settings.STATSD_TAGS_LIKE = None

Enable creating tags as well as the bare version. This causes an ajax view to be stored both as the regular view name and as the ajax tag. Supported separators are _is_ and =

django_statsd.settings.STATSD_HOST = '127.0.0.1'

Statsd host, defaults to 127.0.0.1

django_statsd.settings.STATSD_PORT = 8125

Statsd port, defaults to 8125

django_statsd.settings.STATSD_SAMPLE_RATE = 1.0

Statsd sample rate, lowering this decreases the (random) odds of actually submitting the data. Between 0 and 1 where 1 means always

django_statsd.settings.STATSD_VIEWS_TO_SKIP = ['django.contrib.admin']

List of regular expressions of views to skip

django_statsd.settings.STATSD_TRACK_DATABASE = False

Track database query timings via connection.execute_wrapper. The middleware wraps every configured connection for the duration of each request and submits sql.<alias> timings.

middleware Module

Statsd middleware tracking view, middleware and database timings.

django_statsd.middleware.is_ajax(request)[source]

Recreate the old Django is_ajax check (jQuery-style ajax).

Parameters:

request (HttpRequest)

Return type:

bool

class django_statsd.middleware.WithTimer(timer, key)[source]

Bases: object

Context manager returned by calling a Timer.

Parameters:
class django_statsd.middleware.Client(prefix='view')[source]

Bases: object

Base for the scope’s metric holders.

Collects values during a request and submits them in one go, so a request produces one burst of packets instead of a trickle.

Parameters:

prefix (str)

class_

alias of Client

get_client(*args)[source]

Build a python-statsd client for this prefix plus args.

Parameters:

args (str | None)

Return type:

Any

submit(*args)[source]

Send everything collected. Subclasses define what that means.

Raises:

NotImplementedError – always, on the base class.

Parameters:

args (str | None)

Return type:

None

class django_statsd.middleware.Counter(prefix='view')[source]

Bases: Client

Counters accumulated over one request or task.

Parameters:

prefix (str)

class_

alias of Counter

increment(key, delta=1)[source]

Add delta to key.

Parameters:
Return type:

None

decrement(key, delta=1)[source]

Subtract delta from key.

Parameters:
Return type:

None

submit(*args)[source]

Send every counter that moved. Zeroes are not worth a packet.

Parameters:

args (str | None)

Return type:

None

class django_statsd.middleware.Timer(prefix='view')[source]

Bases: Client

Timings accumulated over one request or task.

A key may be started more than once before it is stopped, so the starts are kept on a stack and the durations add up.

Parameters:

prefix (str)

class_

alias of Timer

start(key)[source]

Start timing key.

Parameters:

key (str)

Return type:

None

stop(key)[source]

Stop timing key and add the elapsed time to its total.

Parameters:

key (str) – The name passed to a matching start().

Returns:

The seconds that elapsed since that start.

Raises:

AssertionError – if key was never started.

Return type:

float

submit(*args)[source]

Send every recorded timing and clear them.

Raises:

AssertionError – under STATSD_DEBUG, if a timer was started and never stopped.

Parameters:

args (str | None)

Return type:

None

class django_statsd.middleware.StatsdMiddleware(get_response)[source]

Bases: object

Opens the scope and submits the per-view metrics.

Goes at the top of MIDDLEWARE, with StatsdMiddlewareTimer at the bottom. The scope lives on asgiref.local.Local, so each request gets its own under both WSGI and ASGI.

Parameters:

get_response (Callable[[HttpRequest], HttpResponseBase])

scope: ClassVar[Local] = <asgiref.local.Local object>
classmethod skip_view(view_name)[source]

Whether view_name matches STATSD_VIEWS_TO_SKIP.

Parameters:

view_name (str)

Return type:

bool

classmethod start(prefix='view')[source]

Open a scope and start the total timer.

Parameters:

prefix (str) – The metric prefix, view for requests and celery for tasks.

Returns:

The scope, which the middleware puts on request.statsd.

Return type:

Local

classmethod stop(*key)[source]

Stop the total timer and submit everything collected.

Parameters:

key (str)

Return type:

None

process_request(request)[source]

Open the scope and hang it off the request.

Parameters:

request (HttpRequest)

Return type:

None

process_view(request, view_func, view_args, view_kwargs)[source]

Name the metric after the view Django resolved.

Parameters:
Return type:

None

process_response(request, response)[source]

Count the status class and submit the request’s metrics.

Parameters:
  • request (HttpRequest)

  • response (HttpResponseBase)

Return type:

HttpResponseBase

process_exception(request, exception)[source]

Stop the timer and count the failure as a 5xx.

Parameters:
Return type:

None

process_template_response(request, response)[source]

Stop the template timer.

Parameters:
  • request (HttpRequest)

  • response (HttpResponseBase)

Return type:

HttpResponseBase

cleanup(request)[source]

Clear the scope so the next request starts fresh.

Parameters:

request (HttpRequest)

Return type:

None

class django_statsd.middleware.StatsdMiddlewareTimer(get_response)[source]

Bases: object

Closes the timers StatsdMiddleware opened.

Goes at the bottom of MIDDLEWARE. Between the pair they time every middleware you install in between.

Parameters:

get_response (Callable[[HttpRequest], HttpResponseBase])

process_request(request)[source]

Stop the inbound timer the tracker started.

Parameters:

request (HttpRequest)

Return type:

None

process_view(request, view_func, view_args, view_kwargs)[source]

Stop the view timer.

Parameters:
Return type:

None

process_response(request, response)[source]

Start the outbound timer the tracker will stop.

Parameters:
  • request (HttpRequest)

  • response (HttpResponseBase)

Return type:

HttpResponseBase

process_exception(request, exception)[source]

Start the exception timer the tracker will stop.

Parameters:
Return type:

None

process_template_response(request, response)[source]

Start the template timer the tracker will stop.

Parameters:
  • request (HttpRequest)

  • response (HttpResponseBase)

Return type:

HttpResponseBase

class django_statsd.middleware.DummyWith[source]

Bases: object

Stands in for WithTimer outside a tracked request.

Lets the module-level helpers be used anywhere without the caller checking whether a request is being timed.

django_statsd.middleware.start(key)[source]

Start timing key in the current scope, if there is one.

Parameters:

key (str)

Return type:

None

django_statsd.middleware.stop(key)[source]

Stop timing key.

Returns:

The elapsed seconds, or None outside a tracked request.

Parameters:

key (str)

Return type:

float | None

django_statsd.middleware.with_(key)[source]

Return a context manager timing key.

Returns:

A timer inside a tracked request, and a no-op outside one.

Parameters:

key (str)

Return type:

WithTimer | DummyWith

django_statsd.middleware.incr(key, value=1)[source]

Add value to the counter key, if a scope is open.

Parameters:
Return type:

None

django_statsd.middleware.decr(key, value=1)[source]

Subtract value from the counter key, if a scope is open.

Parameters:
Return type:

None

django_statsd.middleware.wrapper(prefix, f)[source]

Wrap f so each call is timed as <prefix>.<function name>.

Parameters:
Return type:

Callable[[~P], T]

django_statsd.middleware.named_wrapper(name, f)[source]

Wrap f so each call is timed as name.

Parameters:
Return type:

Callable[[~P], T]

django_statsd.middleware.decorator(prefix)[source]

Return a decorator timing each call under prefix.

Parameters:

prefix (str)

Return type:

Callable[[Callable[[~P], T]], Callable[[~P], T]]

database Module

Database query timing through Django’s execute_wrapper hooks.

Enabled by the STATSD_TRACK_DATABASE setting; StatsdMiddleware wraps every configured connection for the duration of each request and submits the query durations as sql.<alias> timings.

django_statsd.database.statsd_execute_wrapper(alias)[source]

Build an execute wrapper timing queries as sql.<alias>.

Parameters:

alias (str)

Return type:

Callable[[Callable[[str, Any, bool, dict[str, Any]], Any], str, Any, bool, dict[str, Any]], Any]

celery Module

Celery signal integration submitting task counters and timings.

json Module

Time stdlib json calls as json.<function> metrics.

redis Module

Patch redis.Redis to time commands as redis.<command>.

templates Module

Time Django template rendering as render_django metrics.

utils Module

Helpers to build python-statsd connections and clients.

django_statsd.utils.get_connection(host=None, port=None, sample_rate=None, disabled=None)[source]

Build a python-statsd connection, defaulting to the settings.

Parameters:
  • host (str | None)

  • port (int | None)

  • sample_rate (float | None)

  • disabled (bool | None)

Return type:

Any

django_statsd.utils.get_client(name, connection=None, class_=<class 'statsd.client.Client'>)[source]

Build a python-statsd client of class_ named name.

Parameters:
Return type:

Any

django_statsd.utils.get_timer(name, connection=None)[source]

Build a statsd.Timer named name.

Parameters:
Return type:

Any

django_statsd.utils.get_counter(name, connection=None)[source]

Build a statsd.Counter named name.

Parameters:
Return type:

Any