Пример #1
0
  def test_safe_eval(self):
    s = SafeEval()

    r = s.eval('1+1')
    self.assertEqual(r, 2)

    r = s.eval('2*10')
    self.assertEqual(r, 20)

    r = s.eval('0.5 * 4')
    self.assertEqual(r, 2)

    r = s.eval('0.5 * W', {'W': 4})
    self.assertEqual(r, 2)

    r = s.eval(
      '(VCC / 2**10) * W',
      {'W': 500, 'VCC': 5})
    self.assertEqual(int(r*100), 244)

    with self.assertRaises(TypeError):
      r = s.eval('0.5 * S', {'W': 4})

    with self.assertRaises(TypeError):
      r = s.eval('eval("1+1")')
Пример #2
0
def hive_show(request, hive_id, hours=None, datefrom=None):
  h = get_object_or_404(Hive, address=int(hive_id, 16))
  # Get all hive chart for this hive.
  hc = HiveChart.objects.filter(hive=h)
  # And all data for this hive.
  date_now = datetime.utcnow().replace(tzinfo=utc)
  # If user does not give time range, show last 24 hours.
  date = date_now-timedelta(hours=24)

  if datefrom:
    try:
      # Show data from given date until now.
      date = datetime.strptime(datefrom, '%Y-%m-%d')
      # Convert date to timezone set in settings => user's timezone
      date = pytz.timezone(settings.TIME_ZONE).localize(date, is_dst=None)
      # Now, convert datetime to UTC.
      date = date.astimezone(pytz.utc)
    except ValueError:
      # If user gives wrong date, show data from last 24 hour.
      # TODO: show warning to user.
      date = date_now-timedelta(hours=24)
  elif hours:
      # Show data from last 'hours' hours.
      date = date_now-timedelta(hours=int(hours))

  hds = HiveData.objects.filter(hive=h).filter(time__gte=date)

  hive_charts = []
  for c in hc:
    series = []
    for d in c.data:
      variable = HiveVariables.objects.get(keyword=d['variable'])
      data = []
      for hd in hds:
        t = int(time.mktime(timezone.localtime(hd.time).timetuple())*1000)
        s = SafeEval()
        if 'expression' in d:
          try:
            data.append([t, float(s.eval(d['expression'], hd.data))])
          except TypeError:
            # If some data in hs.data are missing, skip them.
            pass
        else:
          data.append([t, float(hd.data[variable.keyword])])

      series.append({
        'name': variable.name,
        'data': sorted(data),
      })

    chart = {
      'settings': c.chart.data,
      'series': series
    }

    hive_charts.append(chart)

  # Show last received data in table
  # TODO: ...
  if len(hds) > 0:
    last_data = {
      'temperature': hds[0].data.get('TO', hds[0].data.get('TE', '0') / 16.0),
      'time': hds[0].time,
      'weight': (hds[0].data.get('W', 0) - 12.7173) / 8.2767,
    }
  else:
    last_data = {
      'temperature': '?',
      'time': None,
      'weight': '?',
    }

  return render_to_response(
    'hive/detail.html',
    {'charts': hive_charts, 'last': last_data},
    context_instance=RequestContext(request)
  )