django-alive


Namedjango-alive JSON
Version 2.0.0 PyPI version JSON
download
home_pagehttps://github.com/lincolnloop/django-alive/
SummaryHealtchecks for Django
upload_time2024-08-30 16:29:00
maintainerNone
docs_urlNone
authorPeter Baumgartner
requires_pythonNone
licenseMIT
keywords django healtcheck alive
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage No coveralls.
            # django-alive 🕺

[![tests](https://github.com/lincolnloop/django-alive/actions/workflows/tox.yml/badge.svg)](https://github.com/lincolnloop/django-alive/actions/workflows/tox.yml)
[![coverage](https://img.shields.io/codacy/coverage/5d539d4956a44f55aec632f3a43ee6c1.svg)](https://app.codacy.com/project/ipmb/django-alive/dashboard)
[![PyPI](https://img.shields.io/pypi/v/django-alive.svg)](https://pypi.org/project/django-alive/)
![Python Versions](https://img.shields.io/pypi/pyversions/django-alive.svg)

Provides two healthcheck endpoints for your Django application:

### Alive

Verifies the WSGI server is responding.

* Default URL: `/-/alive/`
* Success:
    * status code: `200`
    * content: `ok`
* Failure: This view never returns a failure. A failure would mean your WSGI server is not running.

### Health

Verifies services are ready.

* Default URL: `/-/health/`
* Success:
    * status_code: `200`
    * content: `{"healthy": true}`
* Failure:
    * status_code: `503`
    * content: `{"healthy": false, "errors": ["error 1", "error 2"]}`

By default the health endpoint will test the database connection, but can be configured to check the cache, staticfiles, or any additional custom checks.

Supports Django 3.2+ on Python 3.6+.

## Install

```
pip install django-alive
```

## Configure

Add this to your project's `urlpatterns`:

```python
path("-/", include("django_alive.urls"))
```


If you wish to use the `healthcheck` [management command](#management-command), add
`django_alive` to the `INSTALLED_APPS`.

## Enabling Checks

The default "health" endpoint will test a simple `SELECT 1` query on the database. Additional checks can be enabled in your Django settings.

Use the `ALIVE_CHECKS` setting to configure the checks to include. It is a list of tuples with the path to a Python function as a first argiment and dict of keyword arguments to pass to that function as a second argument. A full example:

```python
ALIVE_CHECKS = [
    ("django_alive.checks.check_database", {}),
    ("django_alive.checks.check_staticfile", {
        "filename": "img/favicon.ico",
    }),
    ("django_alive.checks.check_cache", {
        "cache": "session",
        "key": "test123",
    }),
    ("django_alive.checks.check_migrations", {}),
]
```

**⚠️ Warning: Changed in version 1.3.0 ⚠️**

**NOTE:** Old settings with `ALIVE_CHECKS` as dict was deprecated in favor of a list of tuples.


### Built-in Checks

Defined in `django_alive.checks`.

```python
def check_cache(key="django-alive", cache="default")
```

Fetch a cache key against the specified cache.

#### Parameters:

- `key` (`str`):  Cache key to fetch (does not need to exist)
- `cache` (`str`):  Cache alias to execute against

---

```python
def check_database(query="SELECT 1", database="default")
```

Run a SQL query against the specified database.

#### Parameters:

- `query` (`str`):  SQL to execute
- `database` (`str`):  Database alias to execute against

---

```python
def check_migrations(alias=None)
```

Verify all defined migrations have been applied

#### Parameters:

- `alias` (`str`):  An optional database alias (default: check all defined databases)

---

```python
def check_staticfile(filename)
```

Verify a static file is reachable

#### Parameters:

- `filename` (`str`):  static file to verify

## Management Command

In addition to the view, the configured healthchecks can also be run via a management command with `manage.py healthcheck`. This will exit with an error code if all the healthchecks do not pass.

## Custom Checks

`django-alive` is designed to easily extend with your own custom checks. Simply define a function which performs your check and raises a `django_alive.HealthcheckFailure` exception in the event of a failure. See [`checks.py`](https://github.com/lincolnloop/django-alive/blob/master/django_alive/checks.py) for some examples on how to write a check.

## Disabling `ALLOWED_HOSTS` for Healthchecks

Often, load balancers will not pass a `Host` header when probing a healthcheck endpoint. This presents a problem for [Django's host header validation](https://docs.djangoproject.com/en/2.1/topics/security/#host-headers-virtual-hosting). A middleware is included that will turn off the host checking only for the healthcheck endpoints. This is safe since these views never do anything with the `Host` header.

Enable the middleware by inserting this **at the beginning** of your `MIDDLEWARE`:

```python
MIDDLEWARE = [
    "django_alive.middleware.healthcheck_bypass_host_check",
    # ...
]
```

## Handling `SECURE_SSL_REDIRECT`

If your load balancer is doing HTTPS termination and you have `SECURE_SSL_REDIRECT=True` in your settings, you want to make sure that your healtcheck URLs are not also redirected to HTTPS. In that case, add the following to your settings:

```python
SECURE_REDIRECT_EXEMPT = [r"^-/"]  # django-alive URLs
```

2.0.0 (2024-08-30)
------------------

- Allow executing checks multiple times with different parameters; `ALIVE_CHECKS` should now be a list of tuples (setting it to a dictionary results in a deprecation warning).


1.2.2 (2024-08-14)
------------------

- Add GitHub Action for running tests against supported versions
- Release from GitHub Actions


1.2.1 (2021-07-23)
------------------

* Update PyPI metadata


1.2.0 (2021-07-23)
------------------

* Updated test matrix. Python 2 no longer "officially" supported.
* Prevent Traceback in middleware if URLs are not setup


1.1.0 (2019-11-06)
------------------

* Added `healthcheck` management command
* Added optional `check_migrations` healthcheck


1.0.1 (2018-09-10)
------------------

* Documentation improvements
* Python 3.7 support


1.0.0 (2018-08-21)
------------------

* Initial release

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/lincolnloop/django-alive/",
    "name": "django-alive",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "django, healtcheck, alive",
    "author": "Peter Baumgartner",
    "author_email": "pete@lincolnloop.com",
    "download_url": "https://files.pythonhosted.org/packages/22/04/f57684e7b157f4d1c9327284d876da7f04197b7c34308702ec201d9429e2/django_alive-2.0.0.tar.gz",
    "platform": null,
    "description": "# django-alive \ud83d\udd7a\n\n[![tests](https://github.com/lincolnloop/django-alive/actions/workflows/tox.yml/badge.svg)](https://github.com/lincolnloop/django-alive/actions/workflows/tox.yml)\n[![coverage](https://img.shields.io/codacy/coverage/5d539d4956a44f55aec632f3a43ee6c1.svg)](https://app.codacy.com/project/ipmb/django-alive/dashboard)\n[![PyPI](https://img.shields.io/pypi/v/django-alive.svg)](https://pypi.org/project/django-alive/)\n![Python Versions](https://img.shields.io/pypi/pyversions/django-alive.svg)\n\nProvides two healthcheck endpoints for your Django application:\n\n### Alive\n\nVerifies the WSGI server is responding.\n\n* Default URL: `/-/alive/`\n* Success:\n    * status code: `200`\n    * content: `ok`\n* Failure: This view never returns a failure. A failure would mean your WSGI server is not running.\n\n### Health\n\nVerifies services are ready.\n\n* Default URL: `/-/health/`\n* Success:\n    * status_code: `200`\n    * content: `{\"healthy\": true}`\n* Failure:\n    * status_code: `503`\n    * content: `{\"healthy\": false, \"errors\": [\"error 1\", \"error 2\"]}`\n\nBy default the health endpoint will test the database connection, but can be configured to check the cache, staticfiles, or any additional custom checks.\n\nSupports Django 3.2+ on Python 3.6+.\n\n## Install\n\n```\npip install django-alive\n```\n\n## Configure\n\nAdd this to your project's `urlpatterns`:\n\n```python\npath(\"-/\", include(\"django_alive.urls\"))\n```\n\n\nIf you wish to use the `healthcheck` [management command](#management-command), add\n`django_alive` to the `INSTALLED_APPS`.\n\n## Enabling Checks\n\nThe default \"health\" endpoint will test a simple `SELECT 1` query on the database. Additional checks can be enabled in your Django settings.\n\nUse the `ALIVE_CHECKS` setting to configure the checks to include. It is a list of tuples with the path to a Python function as a first argiment and dict of keyword arguments to pass to that function as a second argument. A full example:\n\n```python\nALIVE_CHECKS = [\n    (\"django_alive.checks.check_database\", {}),\n    (\"django_alive.checks.check_staticfile\", {\n        \"filename\": \"img/favicon.ico\",\n    }),\n    (\"django_alive.checks.check_cache\", {\n        \"cache\": \"session\",\n        \"key\": \"test123\",\n    }),\n    (\"django_alive.checks.check_migrations\", {}),\n]\n```\n\n**\u26a0\ufe0f Warning: Changed in version 1.3.0 \u26a0\ufe0f**\n\n**NOTE:** Old settings with `ALIVE_CHECKS` as dict was deprecated in favor of a list of tuples.\n\n\n### Built-in Checks\n\nDefined in `django_alive.checks`.\n\n```python\ndef check_cache(key=\"django-alive\", cache=\"default\")\n```\n\nFetch a cache key against the specified cache.\n\n#### Parameters:\n\n- `key` (`str`):  Cache key to fetch (does not need to exist)\n- `cache` (`str`):  Cache alias to execute against\n\n---\n\n```python\ndef check_database(query=\"SELECT 1\", database=\"default\")\n```\n\nRun a SQL query against the specified database.\n\n#### Parameters:\n\n- `query` (`str`):  SQL to execute\n- `database` (`str`):  Database alias to execute against\n\n---\n\n```python\ndef check_migrations(alias=None)\n```\n\nVerify all defined migrations have been applied\n\n#### Parameters:\n\n- `alias` (`str`):  An optional database alias (default: check all defined databases)\n\n---\n\n```python\ndef check_staticfile(filename)\n```\n\nVerify a static file is reachable\n\n#### Parameters:\n\n- `filename` (`str`):  static file to verify\n\n## Management Command\n\nIn addition to the view, the configured healthchecks can also be run via a management command with `manage.py healthcheck`. This will exit with an error code if all the healthchecks do not pass.\n\n## Custom Checks\n\n`django-alive` is designed to easily extend with your own custom checks. Simply define a function which performs your check and raises a `django_alive.HealthcheckFailure` exception in the event of a failure. See [`checks.py`](https://github.com/lincolnloop/django-alive/blob/master/django_alive/checks.py) for some examples on how to write a check.\n\n## Disabling `ALLOWED_HOSTS` for Healthchecks\n\nOften, load balancers will not pass a `Host` header when probing a healthcheck endpoint. This presents a problem for [Django's host header validation](https://docs.djangoproject.com/en/2.1/topics/security/#host-headers-virtual-hosting). A middleware is included that will turn off the host checking only for the healthcheck endpoints. This is safe since these views never do anything with the `Host` header.\n\nEnable the middleware by inserting this **at the beginning** of your `MIDDLEWARE`:\n\n```python\nMIDDLEWARE = [\n    \"django_alive.middleware.healthcheck_bypass_host_check\",\n    # ...\n]\n```\n\n## Handling `SECURE_SSL_REDIRECT`\n\nIf your load balancer is doing HTTPS termination and you have `SECURE_SSL_REDIRECT=True` in your settings, you want to make sure that your healtcheck URLs are not also redirected to HTTPS. In that case, add the following to your settings:\n\n```python\nSECURE_REDIRECT_EXEMPT = [r\"^-/\"]  # django-alive URLs\n```\n\n2.0.0 (2024-08-30)\n------------------\n\n- Allow executing checks multiple times with different parameters; `ALIVE_CHECKS` should now be a list of tuples (setting it to a dictionary results in a deprecation warning).\n\n\n1.2.2 (2024-08-14)\n------------------\n\n- Add GitHub Action for running tests against supported versions\n- Release from GitHub Actions\n\n\n1.2.1 (2021-07-23)\n------------------\n\n* Update PyPI metadata\n\n\n1.2.0 (2021-07-23)\n------------------\n\n* Updated test matrix. Python 2 no longer \"officially\" supported.\n* Prevent Traceback in middleware if URLs are not setup\n\n\n1.1.0 (2019-11-06)\n------------------\n\n* Added `healthcheck` management command\n* Added optional `check_migrations` healthcheck\n\n\n1.0.1 (2018-09-10)\n------------------\n\n* Documentation improvements\n* Python 3.7 support\n\n\n1.0.0 (2018-08-21)\n------------------\n\n* Initial release\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Healtchecks for Django",
    "version": "2.0.0",
    "project_urls": {
        "Homepage": "https://github.com/lincolnloop/django-alive/"
    },
    "split_keywords": [
        "django",
        " healtcheck",
        " alive"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7d5548839b7a01d8ad2f084b5c3a76a5acd5c7e4f3dc8d8fe7def35154a8f5c8",
                "md5": "a90fdd0d142361af3dbe7ab37d087f95",
                "sha256": "c8e5a767080566aefac6b05d60e4371871f292e0e32a753b6c18b8c28f473c3e"
            },
            "downloads": -1,
            "filename": "django_alive-2.0.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "a90fdd0d142361af3dbe7ab37d087f95",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 11796,
            "upload_time": "2024-08-30T16:28:59",
            "upload_time_iso_8601": "2024-08-30T16:28:59.172516Z",
            "url": "https://files.pythonhosted.org/packages/7d/55/48839b7a01d8ad2f084b5c3a76a5acd5c7e4f3dc8d8fe7def35154a8f5c8/django_alive-2.0.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2204f57684e7b157f4d1c9327284d876da7f04197b7c34308702ec201d9429e2",
                "md5": "05924b50be9438f80c8c39d514c7eb5a",
                "sha256": "f7aa691db23b1065bdbaee96d8c347e3d9df2be783c9d5514f7fd82e9c9ee088"
            },
            "downloads": -1,
            "filename": "django_alive-2.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "05924b50be9438f80c8c39d514c7eb5a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 11016,
            "upload_time": "2024-08-30T16:29:00",
            "upload_time_iso_8601": "2024-08-30T16:29:00.700781Z",
            "url": "https://files.pythonhosted.org/packages/22/04/f57684e7b157f4d1c9327284d876da7f04197b7c34308702ec201d9429e2/django_alive-2.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-08-30 16:29:00",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "lincolnloop",
    "github_project": "django-alive",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "django-alive"
}
        
Elapsed time: 1.48451s