Created
August 4, 2016 19:35
-
-
Save joeljames/d76b30100c57b91d3a2cc78dcf14b970 to your computer and use it in GitHub Desktop.
Health App View
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
from django.views.generic.base import TemplateResponseMixin, View | |
from rest_framework import status | |
from annoying.functions import get_config | |
from redis import StrictRedis | |
__all__ = [ | |
'StatusQueueView', | |
] | |
class StatusQueueView(TemplateResponseMixin, | |
View): | |
status_queue_template_name = 'health/status_queue.djhtml' | |
def get(self, request): | |
context = self._get_queue_context() | |
queue_summary = context['queue_summary'] | |
if self._is_queue_size_within_range(queue_summary): | |
return self.response_class( | |
request=self.request, | |
template=self.status_queue_template_name, | |
context=context | |
) | |
return self.response_class( | |
request=self.request, | |
template=self.status_queue_template_name, | |
context=context, | |
status=status.HTTP_503_SERVICE_UNAVAILABLE | |
) | |
def _get_queue_context(self): | |
queue_names = get_config('MOINITOR_QUEUES') | |
queue_summary = self._get_queue_summary(queue_names) | |
return { | |
'queue_summary': dict(queue_summary) | |
} | |
def _is_queue_size_within_range(self, queue_summary): | |
allowable_max_queue_size = get_config('ALLOWABLE_MAX_QUEUE_SIZE') | |
for name, size in queue_summary.items(): | |
if size > allowable_max_queue_size: | |
return False | |
return True | |
def get_queue_summary(self, queue_names, connection=None): | |
""" | |
Gets the queue size for the specified `queue_names`. | |
:queue_names: A list of queue names who's size | |
has to be determined (required). | |
:connection: The connection to the client where the queue | |
is stored, defaults to redis. | |
""" | |
connection = connection or StrictRedis.from_url(get_config('REDIS_URL')) | |
summary = defaultdict(int) | |
for queue_name in queue_names: | |
summary[queue_name] = connection.llen(queue_name) | |
return summary |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment