Esempio n. 1
0
  def _from_json(outer_self, value):
    class ObjectAccessor(dict):
      def __getattr__(self, name):
        if name in outer_self._fields:
          return self.get(name)
        else:
          raise AttributeError("no such attribute: " + name)
      
      def __setattr__(self, name, value):
        if name in outer_self._fields:
          self[name] = value
        else:
          raise AttributeError("no such attribute: " + name)

      def __delattr__(self, name):
        if name in outer_self._fields:
          if name in self:
            del self[name]
        else:
          raise AttributeError("no such attribute: " + name)

      def __repr__(self):
        return "[Object: {}]".format(outer_self.name(1))
    for name in value:
      if name not in outer_self._fields:
        raise ValidationFailed("unexpected field '{}'".format(name))
    d = {}
    for name, t in outer_self._fields.items():
      with context.member(name):
        d[name] = t.from_json(value.get(name))
    return ObjectAccessor(**d)
Esempio n. 2
0
 def _check(self, value):
   if value is None:
     raise ValidationFailed("expected Object")
   reasons = []
   for name, t in self._fields.items():
     subvalue = value.get(name)
     try:
       with context.member(name):
         run_check(t.check, subvalue)
     except ValidationFailed as e:
       if subvalue is None:
         reasons.append(ValidationFailed("missing field '{}'".format(name)))
       else:
         reasons.append(e)
   for name in value.__dict__:
     if name not in self._fields:
       reasons.append(ValidationFailed("unexpected field '{}'".format(name)))
   if reasons:
     if len(reasons) == 1:
       raise reasons[0]
     raise ValidationFailed(", ".join(r.format() for r in reasons))