MyHost / src / hosts /

# -*- coding: utf-8 -*-

from datetime import timedelta
import json
from django.http import HttpResponse, HttpResponseRedirect
from django.template.context import RequestContext
from django.utils import timezone
from django.shortcuts import render_to_response, get_object_or_404

from django.views.generic import DetailView
from hosts.models import (Host, CPU, MyHostUser, Vendor, RAM, NetworkCard,
                          GraphicBoard, BIOS,)

class HostDetails(DetailView):
    """generic view for Host"""
    model = Host
    context_object_name = 'host'

    def get_slug_field(self):
        return 'name'

    def get_context_data(self, **kwargs):
        context = super(HostDetails, self).get_context_data(**kwargs)
        context['now'] =
        context['hosts'] = [e[0] for e in Host.objects.all().values_list('name')]
        context['status_last_ping'] = get_currentness(self.object.time_last_ping)
        if self.object.tapper:
            context['status_tapper'] = get_currentness(self.object.tapper.time_last_update)
            context['status_tapper'] = 'no-tapper'
        return context

def get_currentness(date, delta_warning=60, delta_alarm=240):
    Return the currentness of the given date compared to the current time
    :param date:  date object that is going to be compared,
                  has to be time zone aware
    :param delta_warning: timedelta in minutes for state warning
    :param delta_alarm: timedelta in minutes for state alarm
    :return: one of 'ok', 'warning', 'alarm' Note, 'alarm' is returned
             if date is None (That is if the host has never been updated.)
    if not date:
        return 'alarm'
    status = 'ok'
    time_diff = - date
    if time_diff > (timedelta(minutes=delta_warning)):
        status = "warning"
    if time_diff > (timedelta(minutes=delta_alarm)):
        status = "alarm"
    return status

def get_host_names_as_json(request):
    """return active Sponsors as json
    #response = HttpResponse()
    #response['Content-Type'] = "text/javascript; charset=utf-8"

    hosts = [e[0] for e in Host.objects.all().values_list('name')]

    #response_data = [
    #    { "content": "<div class='slide_inner'><img class='photo' src='%s' "
    #      "alt=''></div>" % (settings.MEDIA_URL + str(s.picture))} \
    #    for s in pictures
    #response_daa = [
    #    {"src": "{0}".format(settings.MEDIA_URL + str(s.picture))} \
    #        for s in pictures

    return HttpResponse(json.dumps(hosts), mimetype="application/json")