summaryrefslogtreecommitdiff
path: root/ebus/web/controller.py
blob: 683bb6c4cc5ba3908ae59639b1ac9556c61ea036 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, time
import itty
from werkzeug.contrib.cache import SimpleCache
from simplejson import dumps as dump_json
from sqlalchemy.orm import sessionmaker

from ebus import model

Session = sessionmaker()

class CacheDecorator(object):
    def __init__(self,key,timeout=20): 
        self.cache = SimpleCache(default_timeout=timeout)
        self.func = None
        self.key = key

    def cachedFunc(self, *args, **kwargs):
        key = self.key(args, kwargs)
        ret = self.cache.get(key)
        if ret is None:
            ret = self.func(*args, **kwargs)
            self.cache.set(key, ret)
        return ret

    def __call__(self, func): 
        self.func = func 
        return self.cachedFunc


## Web Requests
@itty.get("/")
def index(req):
    filename=os.path.join(os.path.dirname(__file__), "static", "index.html")
    return open(filename,"r").read()

@itty.get('/json/(?P<sensor>[^/]+)')
@itty.get('/json/(?P<sensor>[^/]+)/from_date/(?P<from_date>[^/]+)')
@itty.get('/json/(?P<sensor>[^/]+)/from_date/(?P<from_date>[^/]+)/till_date/(?P<till_date>[^/]+)')
@CacheDecorator(key=lambda args,kwargs: tuple(kwargs.keys()) + tuple(kwargs.values()), 
                timeout=20)
def json(req,sensor=None,from_date=None,till_date=None):
    print "sensor=%s from_date=%s till_date=%s" % (sensor,from_date,till_date)
    values = Session().query(model.Value).join(model.Sensor)

    if sensor:
        values = values.filter(model.Sensor.name == sensor)\

    if from_date:
        values = values.filter(model.Value.timestamp >= from_date)

    if till_date:
        values = values.filter(model.Value.timestamp <= till_date)

    response = {"sensor":sensor, "from_date":from_date, "till_date":till_date, "values":values.all()}
    return itty.Response(dump_json(response),
                         content_type="application/json")

@itty.get("/static/(?P<filename>.+)")
def static(request,filename):
    file = itty.static_file(filename, root=os.path.join(os.path.dirname(__file__), 'static'))
    return itty.Response(file, content_type=itty.content_type(file))



## Start method
def run(db_engine,host="0.0.0.0",port=5000):
    Session.configure(bind=db_engine)
    return itty.run_itty(host=host,port=port)