Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include API endpoint, to access current value as well as percentage #8

Merged
merged 1 commit into from
Dec 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions homometer/views.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
from django.shortcuts import render
from django.db.models import Sum
from django.http import JsonResponse
from django.views.decorators.clickjacking import xframe_options_exempt
from math import floor

from .models import Stat


def index(request, minimal=False):
def getCurrentAndPercent():
# It would be nice if the aggregate function could return a default value when
# there are no rows: https://code.djangoproject.com/ticket/10929
current = Stat.objects.aggregate(Sum('current'))['current__sum'] or 0

# clip current to range [0, 1500] and convert to percent
percent = (sorted([0, current, 1500])[1] / 1500) * 100
return current, percent


def index(request, minimal=False):
current, percent = getCurrentAndPercent()

# determine homometer color
colors = ['#2dde57', '#2dde57', '#2dde57', '#f3ad4e', '#f3ad4e', '#f3ad4e', '#f3ad4e', '#ed0009', '#ed0009', '#ed0009', '#ed0009']
Expand All @@ -31,3 +35,7 @@ def index(request, minimal=False):
@xframe_options_exempt
def index_minimal(request):
return index(request, minimal=True)

def api(request):
current, percent = getCurrentAndPercent()
return JsonResponse({"current": current, "percent": percent})
1 change: 1 addition & 0 deletions mensa/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@
urlpatterns = [
path('admin/', admin.site.urls),
path('minimal/', views.index_minimal, name='index_minimal'),
path('api/', views.api),
path('', views.index, name='index'),
]