Example #1
0
 def to_python(self, value):
   """Convert our string value to JSON after we load it from the DB"""
   if not value:
     return {}
   elif isinstance(value, basestring):
     res = kbjson.loads(value)
     assert isinstance(res, dict)
     return JSONDict(**res)
   else:
     return value
Example #2
0
def DecodeEvent(msg):
  if isinstance(msg, basestring):
    msg = kbjson.loads(msg)
  event_name = msg.get('event')
  if event_name not in EVENT_NAME_TO_CLASS:
    raise ValueError, "Unknown event: %s" % event_name
  inst = EVENT_NAME_TO_CLASS[event_name]()
  for k, v in msg['data'].iteritems():
    setattr(inst, k, v)
  return inst
Example #3
0
  def found_terminator(self):
    strbuf = self._ibuffer.getvalue()
    self._ibuffer.seek(0)
    self._ibuffer.truncate()

    if not strbuf:
      self._logger.warning('Received empty message')
      return

    try:
      message_dict = kbjson.loads(strbuf)
    except ValueError:
      self._logger.warning('Received malformed message, dropping.')
      return

    # Distinguish between requests, responses, and notifications, using JSON-RPC
    # v2.0 rules
    # (http://groups.google.com/group/json-rpc/web/json-rpc-1-2-proposal):

    self._logger.debug('Received message: %s' % message_dict)
    self.HandleNotification(message_dict)
Example #4
0
def restore(input_fp, kbsite, log_cb=_no_log):
  def _log(obj):
    obj_cls = obj.__class__
    obj_name = obj_cls.__name__
    log_cb('  +++ %s: %s' % (obj_name, obj))

  data = kbjson.loads(input_fp.read())

  kbsite.gates.all().delete()
  for rec in data['gates']:
    gate = models.Gate(site=kbsite, seqn=int(rec.id))
    gate.name = rec.name
    gate.description = rec.get('description')
    gate.save()
    _log(gate)

  user_map = {}
  for rec in data.get('users', []):
    user = None

    # If there's already a user registered with this e-mail address, use it.
    if rec.email:
      user_qs = models.User.objects.filter(email=rec.email)
      if user_qs.count():
        user = user_qs[0]
        user_map[rec.username] = user
        _log(user)
        continue

    # Create a new user, creating a new unique username if necessary.
    iter = 0
    username = rec.username
    while True:
      username_qs = models.User.objects.filter(username=username)
      if not username_qs.count():
        break
      iter += 1
      username = '******' % (rec.username[:30], iter)

    user = models.User(username=username)
    user.first_name = rec.first_name
    user.last_name = rec.last_name
    user.email = rec.email
    user.password = rec.password
    user.is_active = rec.is_active
    user.last_login = rec.last_login
    user.date_joined = rec.date_joined

    # XXX non-prod
    user.is_staff = rec.is_staff
    user.is_superuser = rec.is_superuser

    user.save()
    user_map[rec.username] = user
    _log(user)

  for rec in data.get('profiles', []):
    user = user_map.get(rec.username)
    if not user:
      print 'Warning: profile for non-existant user: %s' % rec.username
      continue
    profile, created = models.UserProfile.objects.get_or_create(user=user)
    profile.gender = rec.gender
    profile.weight = rec.weight
    profile.save()
    _log(profile)

  kbsite.tokens.all().delete()
  for rec in data.get('tokens', []):
    token = models.AuthenticationToken(site=kbsite, seqn=int(rec.id))
    token.auth_device = rec.auth_device
    token.token_value = rec.token_value
    username = rec.get('username')
    if username:
      token.user = user_map[username]
    token.enabled = rec.enabled
    token.created = rec.created_time
    token.pin = rec.get('pin')
    token.save()
    _log(token)

  kbsite.entries.all().delete()
  for rec in data.get('entries', []):
    entry = models.Entry(site=kbsite, seqn=int(rec.id))
    entry.starttime = rec.pour_time
    entry.duration = rec.get('duration')
    entry.status = rec.status
    username = rec.get('user_id')
    if username:
      entry.user = user_map[username]
    entry.auth_token = rec.get('auth_token')
    entry.save()
    _log(entry)

  log_cb('Regenerating sessions ...')
  _RegenSessions(kbsite)
  log_cb('Regenerating stats ...')
  _RegenStats(kbsite)
  log_cb('Regenerating events ...')
  _RegenEvents(kbsite)