Exemple #1
0
def index(request):
    context = RequestContext(request)
    try:
        page = kegweb_models.Page.objects.get(name__exact="MainPage", status__exact="published")
    except kegweb_models.Page.DoesNotExist:
        page = None
    context["page_node"] = page
    context["taps"] = request.kbsite.taps.all()

    try:
        session = request.kbsite.sessions.latest()
        if session.IsActiveNow():
            context["current_session"] = session
    except models.DrinkingSession.DoesNotExist:
        pass

    recent_images = models.Picture.objects.filter(site=request.kbsite, drink__isnull=False).order_by("-time")[:9]
    context["recent_images"] = recent_images

    events = request.kbsite.events.all()[:10]
    context["initial_events"] = kbjson.dumps([protolib.ToDict(e, full=True) for e in events], indent=None)

    sessions = request.kbsite.sessions.all().order_by("-seqn")[:10]
    context["initial_sessions"] = kbjson.dumps([protolib.ToDict(s, full=True) for s in sessions], indent=None)

    return render_to_response("index.html", context)
Exemple #2
0
def py_to_json(f):
  """Decorator that wraps an API method.

  The decorator transforms the method in a few ways:
    - The raw return value from the method is converted to a serialized JSON
      result.
    - The result is wrapped in an outer dict, and set as the value 'result'
    - If an exception is thrown during the method, it is converted to a protocol
      error message.
  """
  def new_function(*args, **kwargs):
    request = args[0]
    http_code = 200
    indent = 2
    if 'indent' in request.GET:
      if request.GET['indent'] == '':
        indent = None
      else:
        try:
          indent_val = int(request.GET['indent'])
          if indent_val >= 0 and indent_val <= 8:
            indent = indent_val
        except ValueError:
          pass
    try:
      result_data = {'result' : f(*args, **kwargs)}
    except Exception, e:
      if settings.DEBUG and 'deb' in request.GET:
        raise
      result_data, http_code = ToJsonError(e)
    return HttpResponse(kbjson.dumps(result_data, indent=indent),
        mimetype='application/json', status=http_code)
Exemple #3
0
 def get_db_prep_save(self, value, connection):
   """Convert our JSON object to a string before we save"""
   if not value:
     return super(JSONField, self).get_db_prep_save("", connection=connection)
   else:
     return super(JSONField, self).get_db_prep_save(kbjson.dumps(value),
         connection=connection)
Exemple #4
0
 def do_GET(self):
     self._ExtractParams()
     client = self.server.client
     result = {
         'ok': False,
     }
     username = self.params.get('username')
     if username:
         username = username[0]
     if self.path == '/add' and username:
         self.server._logger.info('adding: %s' % username)
         client.SendAuthTokenAdd(FLAGS.tap_name, 'core.user', username)
         result['ok'] = True
     elif self.path == '/remove' and username:
         self.server._logger.info('removing: %s' % username)
         client.SendAuthTokenRemove(FLAGS.tap_name, 'core.user', username)
         result['ok'] = True
     elif self.path == '/flows':
         result['ok'] = True
         flow_dict = dict((k, v.ToDict()['data'])
                          for k, v in self.server.client.flows.iteritems())
         result['flows'] = flow_dict
     elif self.path == '/status':
         result['ok'] = True
     body = kbjson.dumps(result)
     if self.callback:
         body = '%s(%s)' % (self.callback, body)
     return self._DoResponse(body=body, type="application/json")
Exemple #5
0
def py_to_json(f):
    """Decorator that wraps an API method.

  The decorator transforms the method in a few ways:
    - The raw return value from the method is converted to a serialized JSON
      result.
    - The result is wrapped in an outer dict, and set as the value 'result'
    - If an exception is thrown during the method, it is converted to a protocol
      error message.
  """
    def new_function(*args, **kwargs):
        request = args[0]
        http_code = 200
        indent = 2
        if 'indent' in request.GET:
            if request.GET['indent'] == '':
                indent = None
            else:
                try:
                    indent_val = int(request.GET['indent'])
                    if indent_val >= 0 and indent_val <= 8:
                        indent = indent_val
                except ValueError:
                    pass
        try:
            result_data = {'result': f(*args, **kwargs)}
        except Exception, e:
            if settings.DEBUG and 'deb' in request.GET:
                raise
            result_data, http_code = ToJsonError(e, sys.exc_info())
        return HttpResponse(kbjson.dumps(result_data, indent=indent),
                            mimetype='application/json',
                            status=http_code)
Exemple #6
0
 def do_GET(self):
   self._ExtractParams()
   client = self.server.client
   result = {
     'ok': False,
   }
   username = self.params.get('username')
   if username:
     username = username[0]
   if self.path == '/add' and username:
     self.server._logger.info('adding: %s' % username)
     client.SendAuthTokenAdd(FLAGS.tap_name, 'core.user', username)
     result['ok'] = True
   elif self.path == '/remove' and username:
     self.server._logger.info('removing: %s' % username)
     client.SendAuthTokenRemove(FLAGS.tap_name, 'core.user', username)
     result['ok'] = True
   elif self.path == '/flows':
     result['ok'] = True
     flow_dict = dict((k, v.ToDict()['data']) for k, v in self.server.client.flows.iteritems())
     result['flows'] = flow_dict
   elif self.path == '/status':
     result['ok'] = True
   body = kbjson.dumps(result)
   if self.callback:
     body = '%s(%s)' % (self.callback, body)
   return self._DoResponse(body=body, type="application/json")
Exemple #7
0
def post_webhook_event(hook_url, event_list):
  post_data = kbjson.dumps({'events': [protolib.ToDict(e) for e in event_list]})
  post_data = urlencode({'payload': post_data})
  opener = urllib2.build_opener()
  opener.addheaders = [
    ('User-agent', 'Kegbot/%s' % util.kegbot_version()),
  ]
  try:
    opener.open(hook_url, data=post_data, timeout=5)
    return True
  except urllib2.URLError:
    return False
def dump(output_fp, kbsite, indent=None, log_cb=_no_log):
  """Produce a dump of this Kegbot system to the given filestream.

  In its current format, the dump is plaintext JSON string consisting of all
  important data, including tap configuration, drink history, and user account
  details.

  All "derived" tables are NOT backed up.  These are tables with data that can
  be regenerated at any time without any loss of history.  Specifically:
    - session chunks
    - user session chunks
    - keg session chunks
    - keg stats
    - user stats
    - session stats
    - system events
  """
  res = {}
  items = (
      ('bdb_brewers', bdb_models.Brewer.objects.all()),
      ('bdb_styles', bdb_models.BeerStyle.objects.all()),
      ('bdb_beertypes', bdb_models.BeerType.objects.all()),
      ('thermosensors', kbsite.thermosensors.all().order_by('id')),
      ('kegs', kbsite.kegs.all().order_by('id')),
      ('taps', kbsite.taps.all().order_by('id')),
      ('sessions', kbsite.sessions.all().order_by('id')),
      ('thermologs', kbsite.thermologs.all().order_by('-id')[:60*24]),
      ('thermosummarylogs', kbsite.thermosummarylogs.all().order_by('id')),
      ('users', models.User.objects.all().order_by('id')),
      ('profiles', models.UserProfile.objects.all().order_by('id')),
      ('drinks', kbsite.drinks.valid().order_by('id')),
      ('tokens', kbsite.tokens.all().order_by('id')),
  )

  log_cb('Generating backup data ...')
  for name, qs in items:
    log_cb('  .. dumping %s' % name)
    res[name] = list(protolib.ToDict(qs, full=True))

  log_cb('Serializing and writing backup data ...')
  output_fp.write(kbjson.dumps(res, indent=indent))
Exemple #9
0
def py_to_json(f):
    """Decorator that wraps an API method.

  The decorator transforms the method in a few ways:
    - The raw return value from the method is converted to a serialized JSON
      result.
    - The result is wrapped in an outer dict, and set as the value 'result'
    - If an exception is thrown during the method, it is converted to a protocol
      error message.
  """

    @never_cache
    def new_function(*args, **kwargs):
        request = args[0]
        http_code = 200
        indent = 2
        if "indent" in request.GET:
            if request.GET["indent"] == "":
                indent = None
            else:
                try:
                    indent_val = int(request.GET["indent"])
                    if indent_val >= 0 and indent_val <= 8:
                        indent = indent_val
                except ValueError:
                    pass
        try:
            result_data = prepare_data(f(*args, **kwargs))
            result_data["meta"] = {"result": "ok"}
        except Exception, e:
            exc_info = sys.exc_info()
            if settings.DEBUG and "deb" in request.GET:
                raise exc_info[1], None, exc_info[2]
            result_data, http_code = ToJsonError(e, exc_info)
            result_data["meta"] = {"result": "error"}
        return HttpResponse(kbjson.dumps(result_data, indent=indent), mimetype="application/json", status=http_code)
Exemple #10
0
 def __repr__(self):
   return kbjson.dumps(self)
Exemple #11
0
 def get_db_prep_save(self, value):
     """Convert our JSON object to a string before we save"""
     if not value:
         return super(JSONField, self).get_db_prep_save("")
     else:
         return super(JSONField, self).get_db_prep_save(kbjson.dumps(value))
Exemple #12
0
 def ToJson(self, indent=2):
     return kbjson.dumps(self.ToDict(), indent=indent)
Exemple #13
0
def post_webhook_event(hook_url, event_list):
  post_data = kbjson.dumps({'events': event_list})
  post_data = urlencode({'payload': post_data})
  # TODO(mikey): set user agent to Kegbot.
  urllib2.urlopen(hook_url, data=post_data)
  return True
class ChartNode(Node):
    CHART_TMPL = '''
  <!-- begin chart %(chart_id)s -->
  <div id="chart-%(chart_id)s-container"
      style="height: %(height)spx; width: %(width)spx;"
      class="kb-chartbox"></div>
  <script type="text/javascript">
    var chart_%(chart_id)s;
    $(document).ready(function() {
      var chart_data = %(chart_data)s;
      chart_%(chart_id)s = new Highcharts.Chart(chart_data);
    });
  </script>
  <!-- end chart %(chart_id)s -->

  '''
    ERROR_TMPL = '''
  <!-- begin chart %(chart_id)s -->
  <div id="chart-%(chart_id)s-container"
      style="height: %(height)spx; width: %(width)spx;"
      class="kb-chartbox-error">
    %(error_str)s
  </div>
  <!-- end chart %(chart_id)s -->
  '''

    def __init__(self, charttype, width, height, args):
        self._charttype = charttype
        self._width = width
        self._height = height
        self._args = args

        try:
            self._chart_fn = getattr(self, 'chart_%s' % (self._charttype, ))
        except AttributeError:
            raise TemplateSyntaxError('unknown chart type: %s' %
                                      self._charttype)

    def _get_chart_id(self, context):
        # TODO(mikey): Is there a better way to store _CHART_ID?
        if not hasattr(context, '_CHART_ID'):
            context._CHART_ID = 0
        context._CHART_ID += 1
        return context._CHART_ID

    def render(self, context):
        chart_id = self._get_chart_id(context)

        width = self._width
        height = self._height

        obj = Variable(self._args[0]).resolve(context)
        try:
            chart_result = self._chart_fn(obj)
        except charts.ChartError, e:
            error_str = 'chart error: %s' % (e, )
            return ChartNode.ERROR_TMPL % vars()
        chart_base = {
            'chart': {
                'borderColor': '#eeeeff',
                'borderWidth': 0,
                'renderTo': 'chart-%s-container' % chart_id,
            },
            'credits': {
                'enabled': False,
            },
            'legend': {
                'enabled': False,
            },
            'margin': [0, 0, 0, 0],
            'title': {
                'text': None,
            },
            'yAxis': {
                'labels': {
                    'align': 'left'
                },
                'title': {
                    'text': None,
                }
            },
        }

        chart_data = chart_base
        for k, v in chart_result.iteritems():
            if k not in chart_data:
                chart_data[k] = v
            elif type(v) == type({}):
                chart_data[k].update(v)
            else:
                chart_data[k] = v
        chart_data = kbjson.dumps(chart_data, indent=None)
        return ChartNode.CHART_TMPL % vars()
Exemple #15
0
 def ToJson(self, indent=2):
   return kbjson.dumps(self.ToDict(), indent=indent)
Exemple #16
0
def post_webhook_event(hook_url, event_list):
    post_data = kbjson.dumps({'events': event_list})
    post_data = urlencode({'payload': post_data})
    # TODO(mikey): set user agent to Kegbot.
    urllib2.urlopen(hook_url, data=post_data)
    return True
Exemple #17
0
 def __repr__(self):
     return kbjson.dumps(self)