Commit 0a64d6bd authored by Alan Trick's avatar Alan Trick

Initial commit

parents
Pipeline #36544566 passed with stage
in 1 minute and 5 seconds
[run]
source = django_adminstats
branch = 1
[report]
omit = *tests*,*migrations*
exclude_lines =
pragma: no cover
def __repr__
if self.debug:
raise AssertionError
raise NotImplementedError
except LookupError
except ImportError
allow_migrate_model
*.pyc
.project
.pydevproject
.pytest_cache
.settings
dist
build
*.egg-info
.idea
.coverage
.tox
AUTHORS
ChangeLog
coverage.xml
.eggs
\ No newline at end of file
image: python:3.6
variables:
PIP_CACHE_DIR: "$CI_PROJECT_DIR/pip-cache"
cache:
paths:
- "$CI_PROJECT_DIR/pip-cache"
key: "$CI_PROJECT_ID"
before_script:
- python -V
test:
script:
- pip install -U pip setuptools
- pip install -e .[test]
- tox
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
.PHONY: flake8 test coverage
flake8:
flake8 django_adminstats tests
isort:
isort -rc django_adminstats tests
isort_check_only:
isort -rc -c django_adminstats tests
test:
pytest tests/
demo:
DJANGO_SETTINGS_MODULE=tests.demo_settings \
PYTHONPATH="${PYTHONPATH}:." \
django-admin runserver
coverage:
pytest --cov=django_adminstats tests/
==================
Django Admin Stats
==================
|pipeline-badge| |coverage-badge| |pypi-badge|
Django Admin Stats allows you to create and display charts of your data
using the django admin. It uses `c3 <https://c3js.org/>`_ to display charts.
Features
--------
* Supports generating statistics from django models and from trackstats_
metrics.
* Also allows for custom statistics generation by making your own
``Registration`` subclass.
* Nice JavaScript charts with c3, falls back to a plain table without
JavaScript.
Limitations
-----------
* One dimension/axis of the chart is always the date. There's no way to
specify a chart that isn’t “by date”.
* There’s no way to add filters to criteria on charts. The recommended
workaround is to use trackstats and store those stats separately.
Installation
------------
Installation is straightforward. Install ``django-adminstats`` with pip, and
then add ``'django_adminstats',`` to your ``INSTALLED_APPS`` setting. You’ll
also want to register some models or trackstat metrics (see Example Code).
Example Code
------------
See ``tests/models.py``.
Demo
----
Just run ``make demo`` and log in with user ``admin`` and password ``admin``.
.. |pipeline-badge| image:: https://gitlab.com/alantrick/django-adminstats/badges/master/pipeline.svg
:target: https://gitlab.com/alantrick/django-adminstats/
:alt: Build Status
.. |coverage-badge| image:: https://gitlab.com/alantrick/django-adminstats/badges/master/coverage.svg
:target: https://gitlab.com/alantrick/django-adminstats/
:alt: Coverage Status
.. |pypi-badge| image:: https://img.shields.io/pypi/v/django_adminstats.svg
:target: https://pypi.org/project/django-adminstats/
:alt: Project on PyPI
.. _trackstats: https://pypi.org/project/django-trackstats/
default_app_config = 'django_adminstats.apps.Config'
import collections
import django.http
from django import forms
from django.conf.urls import url
from django.contrib import admin
from django.core.exceptions import PermissionDenied
from django.template.response import TemplateResponse
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _
from . import models, registry
class CriteriaForm(forms.ModelForm):
stats_key = forms.ChoiceField(choices=registry.REGISTRY.choices())
class CriteriaInline(admin.TabularInline):
form = CriteriaForm
model = models.Criteria
min_num = 1
extra = 0
class ChartAdmin(admin.ModelAdmin):
change_form_template = 'django_adminstats/chart/change_form.html'
inlines = [CriteriaInline]
list_display = ('title', 'chart_type', 'show_action_links')
list_filter = ('chart_type',)
chart_template = 'django_adminstats/chart/chart.html'
class Media:
js = ('django_adminstats/chart_form.js',)
def get_urls(self):
return [
url(
r'^(?P<chart_id>\w+)/chart$',
self.admin_site.admin_view(self.view_chart),
name='django_adminstats_chart'),
] + super().get_urls()
def show_action_links(self, obj):
return format_html(
'<a href="{url}">{text}</a>',
text=_('Show Chart'), url='{}/chart'.format(obj.pk))
show_action_links.short_description = _('Actions')
def view_chart(self, request, chart_id):
if not self.has_change_permission(request):
raise PermissionDenied
chart = self.get_object(request, chart_id) # type: models.Chart
if chart is None:
raise django.http.Http404()
if request.method != 'GET':
return django.http.HttpResponseNotAllowed(('GET',))
chart_header = list(chart.dates())
chart_rows = collections.OrderedDict()
for criteria in chart.criteria.all():
row = [0] * len(chart_header)
for date, count in registry.REGISTRY.count(criteria).items():
try:
date_idx = chart_header.index(date)
row[date_idx] = count
except ValueError:
pass
label = registry.REGISTRY[criteria.stats_key].label
chart_rows[label] = row
context = {
'title': _('View Chart: %s') % chart.title,
'media': self.media,
'add': True,
'change': False,
'has_delete_permission': False,
'has_change_permission': True,
'has_absolute_url': False,
'opts': self.model._meta,
'chart': chart,
'header': chart_header,
'rows': chart_rows,
'save_as': False,
'show_save': True,
}
context.update(self.admin_site.each_context(request))
request.current_app = self.admin_site.name
return TemplateResponse(request, self.chart_template, context)
admin.site.register(models.Chart, ChartAdmin)
from django.apps import AppConfig
class Config(AppConfig):
name = 'django_adminstats'
verbose_name = 'Statistics Charting'
def ready(self):
pass
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Chart',
fields=[
('id', models.AutoField(
auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('title', models.CharField(max_length=200)),
('chart_type', models.CharField(
choices=[('line', 'Line'), ('bar', 'Bar'), ('pie', 'Pie'),
('area-spline', 'Area'), ('scatter', 'Scatter'),
('donut', 'Donut')],
default='line', max_length=10)),
('until_type', models.CharField(
choices=[('t', 'This day/week/month/year'),
('y', 'Last day/week/month/year'),
('s', 'Specific Date')],
default='t', max_length=1)),
('until_date', models.DateField(
default=django.utils.timezone.now)),
('period_count', models.IntegerField()),
('period_step', models.CharField(
choices=[('d', 'Days'), ('m', 'Months'),
('y', 'Years')], default='d', max_length=1)),
],
),
migrations.CreateModel(
name='Criteria',
fields=[
('id', models.AutoField(
auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('stats_key', models.CharField(max_length=200)),
('side', models.CharField(
choices=[('l', 'Left'), ('r', 'Right')],
default='l', max_length=1)),
('chart', models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name='criteria',
to='django_adminstats.Chart')),
],
),
]
import datetime
from dateutil.relativedelta import relativedelta
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
STEP_DAY = 'd'
STEP_MONTH = 'm'
STEP_YEAR = 'y'
class Chart(models.Model):
TYPE_CHOICES = (
('line', _('Line')),
('bar', _('Bar')),
('pie', _('Pie')),
('area-spline', _('Area')),
('scatter', _('Scatter')),
('donut', _('Donut')),
)
UNTIL_CHOICES = (
('t', _('This day/week/month/year')),
('y', _('Last day/week/month/year')),
('s', _('Specific Date')),
)
STEP_CHOICES = (
(STEP_DAY, _('Days')),
(STEP_MONTH, _('Months')),
(STEP_YEAR, _('Years')),
)
title = models.CharField(max_length=200)
chart_type = models.CharField(
max_length=10, choices=TYPE_CHOICES, default='line')
until_type = models.CharField(
max_length=1, choices=UNTIL_CHOICES, default='t')
until_date = models.DateField(default=timezone.now)
period_count = models.IntegerField()
period_step = models.CharField(
max_length=1, choices=STEP_CHOICES, default=STEP_DAY)
def get_end_date(self):
"""Returns the date after the last period"""
if self.until_type in ('t', 'y'):
date = timezone.now().date()
if self.until_type == 'y':
date = date - self.move_delta()
if self.period_step == STEP_MONTH:
if date.month >= 12:
return datetime.date(date.year+1, 1, 1)
return datetime.date(date.year, date.month+1, 1)
if self.period_step == STEP_YEAR:
return datetime.date(date.year+1, 1, 1)
return date + datetime.timedelta(days=1)
return self.until_date + datetime.timedelta(days=1)
def move_delta(self, amount=1):
if self.period_step == STEP_YEAR:
return relativedelta(years=amount)
if self.period_step == STEP_MONTH:
return relativedelta(months=amount)
return relativedelta(days=amount)
def dates(self):
end = self.get_end_date()
reverse_dates = []
delta = self.move_delta()
for _i in range(self.period_count):
end = end - delta
reverse_dates.append(end)
return reversed(reverse_dates)
def span(self):
end = self.get_end_date()
start = end - self.move_delta(self.period_count)
return start, end
def __str__(self):
return self.title
class Criteria(models.Model):
SIDE_CHOICES = (('l', _('Left')), ('r', _('Right')))
chart = models.ForeignKey(
Chart, on_delete=models.CASCADE, related_name='criteria')
stats_key = models.CharField(max_length=200)
side = models.CharField(
max_length=1, choices=SIDE_CHOICES, default='l')
def __str__(self):
return self.stats_key
import collections
import datetime
from typing import Mapping
import django.db.models.functions as db_functions
from django.db.models import Count, DateField
from . import models
class Registration:
date_field = 'date'
def get_queryset(self):
raise NotImplementedError
def get_span_queryset(self, _period_step, start, end):
qs = self.get_queryset().annotate(
_date_field=db_functions.Cast(self.date_field, DateField()))
kwargs = {'_date_field__gte': start, '_date_field__lt': end}
return qs.filter(**kwargs)
def get_group_queryset(self, period_step, start, end):
query = self.get_span_queryset(period_step, start, end)
ann_kwargs = {}
if period_step == models.STEP_DAY:
ann_kwargs['_date'] = db_functions.TruncDay(
self.date_field, output_field=DateField())
ann_kwargs['_month'] = db_functions.TruncMonth(self.date_field)
ann_kwargs['_year'] = db_functions.TruncYear(self.date_field)
if period_step == models.STEP_MONTH:
ann_kwargs['_date'] = db_functions.TruncMonth(
self.date_field, output_field=DateField())
ann_kwargs['_year'] = db_functions.TruncYear(self.date_field)
if period_step == models.STEP_YEAR:
ann_kwargs['_date'] = db_functions.TruncYear(
self.date_field, output_field=DateField())
return query.annotate(**ann_kwargs).values(*ann_kwargs.keys())
def count(self, start, end, period_step) -> Mapping[datetime.date, int]:
group = self.get_group_queryset(period_step, start, end)
result = dict((item['_date'], item['_c']) for item in
group.annotate(_c=Count('id')).values('_c', '_date'))
return result
class Registry(collections.OrderedDict):
def register(self, reg: Registration):
self[reg.key] = reg
def choices(self):
for key, value in self.items():
yield key, value.label
def count(self, criteria):
stats = self[criteria.stats_key]
start, end = criteria.chart.span()
return stats.count(start, end, criteria.chart.period_step)
class ModelRegistration(Registration):
def __init__(self, model):
self.model = model
self.meta = getattr(self.model, '_meta')
if not self.meta:
raise RuntimeError(
'Model {} is missing Meta class'.format(self.model))
def get_queryset(self):
return self.model.objects
@property
def key(self):
return '{}.{}'.format(self.meta.app_label, self.meta.model_name)
@property
def label(self):
return self.meta.verbose_name_plural.title()
class MetricRegistration(Registration):
def __init__(self, metric):
# metric is probably a lazy object
self.metric = metric
lazy_func = getattr(metric, '_setupfunc')
if lazy_func:
contents = lazy_func.__closure__[1].cell_contents
self.ref = contents['ref']
domain = contents['domain']
lazy_func = getattr(domain, '_setupfunc')
if lazy_func:
contents = lazy_func.__closure__[1].cell_contents
self.domain_ref = contents['ref']
else:
self.domain_ref = metric.domain.ref
else:
self.ref = metric.ref
@property
def key(self):
return 'trackstats:{}.{}'.format(self.domain_ref, self.ref)
@property
def label(self):
return '{} {} Stats'.format(self.domain_ref, self.ref).title()
def get_queryset(self):
from trackstats.models import StatisticByDate
return StatisticByDate.objects.filter(metric=self.metric)
def get_span_queryset(self, period_step, start, end):
from trackstats.models import Period
kwargs = {self.date_field + '__gte': start,
self.date_field + '__lt': end}
if period_step == models.STEP_DAY:
kwargs['period'] = Period.DAY
elif period_step == models.STEP_MONTH:
kwargs['period'] == Period.MONTH
else:
# trackstats doesn't actually support year
kwargs['period'] = Period.LIFETIME
return self.get_queryset().filter(**kwargs)
def count(self, start, end, period_step) -> Mapping[datetime.date, int]:
group = self.get_group_queryset(period_step, start, end)
result = dict((item['_date'], item['value']) for item in
group.values('value', '_date'))
return result
REGISTRY = Registry()
def register(registration: Registration):
REGISTRY.register(registration)
def register_model(model):
register(ModelRegistration(model))
def register_metric(metric):
register(MetricRegistration(metric))
def get_registry_ids():
return REGISTRY.keys()
.c3 svg{font:10px sans-serif;-webkit-tap-highlight-color:transparent}.c3 line,.c3 path{fill:none;stroke:#000}.c3 text{-webkit-user-select:none;-moz-user-select:none;user-select:none}.c3-bars path,.c3-event-rect,.c3-legend-item-tile,.c3-xgrid-focus,.c3-ygrid{shape-rendering:crispEdges}.c3-chart-arc path{stroke:#fff}.c3-chart-arc rect{stroke:#fff;stroke-width:1}.c3-chart-arc text{fill:#fff;font-size:13px}.c3-grid line{stroke:#aaa}.c3-grid text{fill:#aaa}.c3-xgrid,.c3-ygrid{stroke-dasharray:3 3}.c3-text.c3-empty{fill:grey;font-size:2em}.c3-line{stroke-width:1px}.c3-circle._expanded_{stroke-width:1px;stroke:#fff}.c3-selected-circle{fill:#fff;stroke-width:2px}.c3-bar{stroke-width:0}.c3-bar._expanded_{fill-opacity:1;fill-opacity:.75}.c3-target.c3-focused{opacity:1}.c3-target.c3-focused path.c3-line,.c3-target.c3-focused path.c3-step{stroke-width:2px}.c3-target.c3-defocused{opacity:.3!important}.c3-region{fill:#4682b4;fill-opacity:.1}.c3-brush .extent{fill-opacity:.1}.c3-legend-item{font-size:12px}.c3-legend-item-hidden{opacity:.15}.c3-legend-background{opacity:.75;fill:#fff;stroke:#d3d3d3;stroke-width:1}.c3-title{font:14px sans-serif}.c3-tooltip-container{z-index:10}.c3-tooltip{border-collapse:collapse;border-spacing:0;background-color:#fff;empty-cells:show;-webkit-box-shadow:7px 7px 12px -9px #777;-moz-box-shadow:7px 7px 12px -9px #777;box-shadow:7px 7px 12px -9px #777;opacity:.9}.c3-tooltip tr{border:1px solid #ccc}.c3-tooltip th{background-color:#aaa;font-size:14px;padding:2px 5px;text-align:left;color:#fff}.c3-tooltip td{font-size:13px;padding:3px 6px;background-color:#fff;border-left:1px dotted #999}.c3-tooltip td>span{display:inline-block;width:10px;height:10px;margin-right:6px}.c3-tooltip td.value{text-align:right}.c3-area{stroke-width:0;opacity:.2}.c3-chart-arcs-title{dominant-baseline:middle;font-size:1.3em}.c3-chart-arcs .c3-chart-arcs-background{fill:#e0e0e0;stroke:#fff}.c3-chart-arcs .c3-chart-arcs-gauge-unit{fill:#000;font-size:16px}.c3-chart-arcs .c3-chart-arcs-gauge-max{fill:#777}.c3-chart-arcs .c3-chart-arcs-gauge-min{fill:#777}.c3-chart-arc .c3-gauge-value{fill:#000}.c3-chart-arc.c3-target g path{opacity:1}.c3-chart-arc.c3-target.c3-focused g path{opacity:1}.c3-drag-zoom.enabled{pointer-events:all!important;visibility:visible}.c3-drag-zoom.disabled{pointer-events:none!important;visibility:hidden}.c3-drag-zoom .extent{fill-opacity:.1}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.