summaryrefslogtreecommitdiff
path: root/sublab_project/sublab_monitor/templatetags/host_status.py
blob: e119f603cceab743ffabd225261935d67561ab5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from django import template
import sublab_monitor

register = template.Library()

class HostStatusNode(template.Node):
    def __init__(self, host):
        self.host = host

    def host_status(self, context):
        if self not in context.render_context:
            try:
                context.render_context[self] = sublab_monitor.Storage('network_status')
            except sublab_monitor.StorageError:
                return None

        storage = context.render_context[self]
        try:
            return storage.get(self.host)
        except sublab_monitor.StorageError:
            return None

    def host_context(self, context):
        context_data = {
            'hostname': self.host,
            'status': self.host_status(context)
        }

        return template.context.Context(context_data, autoescape=context.autoescape)

    def render(self, context):
        t = template.loader.get_template('sublab_monitor/host_status.html')
        c = self.host_context(context)
        return t.render(c)

@register.tag
def host_status(parser, token):
    try:
        tag_name, host = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
                "%r tag requires a single argument" % token.contents.split()[0])
    if not host[0] == host[-1] and host[0] in ('"', "'"):
        raise template.TemplateSyntaxError(
                "%r tag's argument should be in quotes" % token.contents.split()[0])
    return HostStatusNode(host[1:-1])