# WatchTower15 in Django

```sh
pip install "watchtower15[django]"
```

Add the app and its settings. The app’s `ready()` only names the framework in the `User-Agent` (`django/5.2.1`); it builds nothing, and `settings` is read at first use, so import order and `LOGGING` (applied before the app registry is ready) are never a problem.

```python
INSTALLED_APPS = [..., "watchtower15.integrations.django"]

WATCHTOWER15 = {
    "app_info": "billing/2.4.1",
    "metrics": {"allow_list": {"orders.created": "count", "queue.depth": "level"}, "heartbeat": "app.alive"},
    "flush": "background",   # or "per_request" on serverless
}
```

`api_key`, `metrics_token`, `logs_token`, `api_url` and `ingest_url` may be set there too; each left out is read from `WT15_API_KEY` and its four siblings. Keep the credentials in the environment. A `flush` other than `background` or `per_request` is refused with a `ConfigurationError`.

## The shared clients and the aggregator

```python
from watchtower15.integrations import django as wt15

wt15.client().servers.list()          # the sync Client, built at first use
await wt15.async_client().me()        # the AsyncClient, in an async view
wt15.aggregator().increment("orders.created")
```

`client()`, `async_client()` and `aggregator()` are built once per process, lazily. The aggregator has a `Client` of its own that holds the metrics token alone, so a wrong API key never stops counting. Declare every metric key you count in `metrics.allow_list`: a key not listed is never counted. With `flush="per_request"` the aggregator starts no thread.

## Logs

```python
LOGGING = {
    "version": 1,
    "handlers": {"wt15": {"class": "watchtower15.integrations.django.LogHandler", "stream": "billing", "level": "INFO"}},
    "loggers": {"django": {"handlers": ["wt15"]}, "billing": {"handlers": ["wt15"], "level": "INFO"}},
}
```

`LogHandler` is a [`WatchTower15Handler`](https://developer.watchtower15.com/sdks/python/logs/) whose client is the shared one, so `settings.WATCHTOWER15` reaches it (and `WT15_LOGS_TOKEN` supplies the token).

## Flushing per request

On a platform that freezes the process after the response, add the middleware and set `flush` to `per_request`:

```python
MIDDLEWARE = [..., "watchtower15.integrations.django.WatchTower15Middleware"]
```

After each response it sends the open minute’s metrics and drains the log handlers, never raising. It works under WSGI and ASGI; under ASGI the flush runs in a worker thread, so the event loop serves other requests meanwhile. In `background` mode it does nothing.

## Tests

`"fake": True` in `WATCHTOWER15` makes `client()`, `async_client()` and `aggregator()` return the [fakes](https://developer.watchtower15.com/sdks/python/testing/): nothing leaves the process and no credential is needed. `reset()` forgets the settings and the shared objects, for a test that changes `WATCHTOWER15` with `override_settings`.

```python
from django.test import override_settings
from watchtower15.integrations import django as wt15

@override_settings(WATCHTOWER15={"fake": True})
def test_counts_an_order():
    wt15.reset()
    place_order()
    wt15.aggregator().assert_incremented("orders.created")
```

Source: https://developer.watchtower15.com/sdks/python/django/
