Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
pennersr committed Oct 29, 2017
0 parents commit d82a7aa
Show file tree
Hide file tree
Showing 19 changed files with 443 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[run]
include = healthpoint*
101 changes: 101 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# dotenv
.env

# virtualenv
.venv
venv/
ENV/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
18 changes: 18 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
sudo: false
language: python
python:
- "3.4"
- "3.5"
- "3.6"
env:
matrix:
- TOX_ENV=py34-django111
- TOX_ENV=py35-django111
- TOX_ENV=py36-django111
install:
- pip install tox
- pip install "coverage>=3.7.1" coveralls
script: tox -e $TOX_ENV
after_success:
- coverage report
- coveralls
2 changes: 2 additions & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
django-healthpoint was started by Raymond Penners
(<raymond.penners@intenct.nl> or @pennersr) in October 2017.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 Raymond Penners

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
4 changes: 4 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
include AUTHORS
include LICENSE
include README.rst
recursive-include healthpoint *.html *.js *.css
74 changes: 74 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
==============================
Welcome to django-healthpoint!
==============================

.. image:: https://badge.fury.io/py/django-healthpoint.png
:target: http://badge.fury.io/py/django-healthpoint

.. image:: https://travis-ci.org/pennersr/django-healthpoint.png
:target: http://travis-ci.org/pennersr/django-healthpoint

.. image:: https://img.shields.io/pypi/v/django-healthpoint.svg
:target: https://pypi.python.org/pypi/django-healthpoint

.. image:: https://coveralls.io/repos/pennersr/django-healthpoint/badge.png?branch=master
:alt: Coverage Status
:target: https://coveralls.io/r/pennersr/django-healthpoint

.. image:: https://pennersr.github.io/img/bitcoin-badge.svg
:target: https://blockchain.info/address/1AJXuBMPHkaDCNX2rwAy34bGgs7hmrePEr

Keep track of your statistics.

Source code
http://github.com/pennersr/django-healthpoint


Quickstart
==========

Install the app::

# settings.py
INSTALLED_APPS = [
...
'healthpoint'
]

# urls.py
urlpatterns = [
...
url(r'^', include('healthpoint.urls')),
]

Add a module named ``health.py`` to any of your apps. For example::

from datetime import timedelta

from django.contrib.auth.models import User
from django.utils import timezone

from healthpoint.decorators import health_check


@health_check
def user_signup():
last_user = User.objects.last()
time_since_last_signup = timezone.now() - last_user.date_joined
return time_since_last_signup <= timedelta(days=1)


The health checks can be accessed via the ``/health/`` endpoint:

- It executes all health checks, and reports status 200 if all checks succeed, status 500 otherwise.

- If a staff user is logged in, the endpoint reports the result for each individual check::

{
"success": {},
"error": {
"myproject.myapp.health.user_signup": "ERROR"
}
}

- To provide more detail on the result, the ``@health_check`` can return a tuple ``(success:bool, detail:str)``. The detail message will be listed in the result.
15 changes: 15 additions & 0 deletions healthpoint/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""
___ ___ __ __ ___
|__| |__ /\ | | |__| |__) / \ | |\ | |
| | |___ /~~\ |___ | | | | \__/ | | \| |
"""
VERSION = (0, 1, 0, 'final', 0)

__title__ = 'django-healthpoint'
__version_info__ = VERSION
__version__ = '.'.join(map(str, VERSION[:3])) + ('-{}{}'.format(
VERSION[3], VERSION[4] or '') if VERSION[3] != 'final' else '')
__author__ = 'Raymond Penners'
__license__ = 'MIT'
__copyright__ = 'Copyright 2017 Raymond Penners and contributors'
25 changes: 25 additions & 0 deletions healthpoint/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from functools import wraps

from healthpoint.registry import register_health_check


def health_check(f):

@wraps(f)
def wrapper(*args, **kwargs):
try:
result = f(*args, **kwargs)
if isinstance(result, bool):
success, detail = result, 'OK' if result else 'ERROR'
elif isinstance(result, tuple) and len(result) == 2:
success, detail = result
else:
raise ValueError(
'Your @health_check must return'
' a `bool`, or a tuple of (`bool`, `detail`)')
except Exception as e:
success, detail = False, str(e)
return success, detail

register_health_check(wrapper)
return wrapper
22 changes: 22 additions & 0 deletions healthpoint/registry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import importlib

from django.conf import settings


_checks = []
_initialized = False


def get_health_checks():
global _initialized
if not _initialized:
for app in settings.INSTALLED_APPS:
try:
importlib.import_module('{}.health'.format(app))
except ImportError:
pass
return _checks


def register_health_check(f):
_checks.append(f)
Empty file added healthpoint/tests/__init__.py
Empty file.
6 changes: 6 additions & 0 deletions healthpoint/tests/health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from healthpoint.decorators import health_check


@health_check
def failure():
return False, 'This check always fails'
24 changes: 24 additions & 0 deletions healthpoint/tests/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
DATABASE_ENGINE = 'sqlite3'

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}

INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sites',
'django.contrib.auth',
'django.contrib.admin',

'healthpoint',
'healthpoint.tests'
]

ROOT_URLCONF = 'healthpoint.tests.urls'

USE_TZ = True

SECRET_KEY = 'psst'
9 changes: 9 additions & 0 deletions healthpoint/tests/test_views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.core.urlresolvers import reverse
from django.test import TestCase


class HealthTestCase(TestCase):

def test_health(self):
resp = self.client.get(reverse('healthpoint_health'))
self.assertEqual(resp.status_code, 500)
6 changes: 6 additions & 0 deletions healthpoint/tests/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.conf.urls import include, url


urlpatterns = [
url(r'^', include('healthpoint.urls')),
]
8 changes: 8 additions & 0 deletions healthpoint/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.conf.urls import url

from healthpoint import views


urlpatterns = [
url(r'^health/$', views.health, name='healthpoint_health')
]
21 changes: 21 additions & 0 deletions healthpoint/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from django.http import JsonResponse

from healthpoint.registry import get_health_checks


def health(request):
data = {'success': {}, 'error': {}}
status = 200
for health_check in get_health_checks():
success, detail = health_check()
func = '.'.join([
health_check.__module__,
health_check.__qualname__])
data['success' if success else 'error'][func] = detail
if not success:
status = 500
# Only staff members are allowed to see details...
user = getattr(request, 'user', None)
if user is None or not user.is_staff or not user.is_superuser:
data = {}
return JsonResponse(data, status=status)
Loading

0 comments on commit d82a7aa

Please sign in to comment.