Recursive helper for _to_base_type() to convert a message to an entity.

  Args:
    msg: A Message instance.
    modelclass: A Model subclass.

  Returns:
    An instance of modelclass.
430955
def _message_to_entity(msg, modelclass):
  
  ent = modelclass()
  for prop_name, prop in modelclass._properties.iteritems():
    if prop._code_name == 'blob_':  # TODO: Devise a cleaner test.
      continue  # That's taken care of later.
    value = getattr(msg, prop_name)
    if value is not None and isinstance(prop, model.StructuredProperty):
      if prop._repeated:
        value = [_message_to_entity(v, prop._modelclass) for v in value]
      else:
        value = _message_to_entity(value, prop._modelclass)
    setattr(ent, prop_name, value)
  return ent
470338
def to_model
      mv = value.try(:to_model)
      met = effective_time.try(:to_model)
      mtr = temporal_references.collect(&:to_model)
      mso = subset_operators.collect(&:to_model)
      field_values = retrieve_field_values_model_for_model

      retrieve_title_and_description_for_model unless @variable || @derivation_operator

      @code_list_id = nil if @derivation_operator

      # prevent json model generation of empty children and comments
      cc = children_criteria.present? ? children_criteria : nil
      comments = @comments.present? ? @comments : nil

      HQMF::DataCriteria.new(id, title, nil, description, @code_list_id, cc, derivation_operator, @definition, status,
                             mv, field_values, met, retrieve_code_system_for_model, @negation, @negation_code_list_id,
                             mtr, mso, @specific_occurrence, @specific_occurrence_const, @source_data_criteria,
                             comments, @variable)
    end
291856
def __response_message_descriptor(self, message_type, method_id):
    

    # Skeleton response descriptor, common to all response objects
    descriptor = {'200': {'description': 'A successful response'}}

    if message_type != message_types.VoidMessage():
      self.__parser.add_message(message_type.__class__)
      self.__response_schema[method_id] = self.__parser.ref_for_message_type(
          message_type.__class__)
      descriptor['200']['schema'] = {'$ref': '#/definitions/{0}'.format(
          self.__response_schema[method_id])}

    return dict(descriptor)
1142942
def model_factory(abstract_class):
    
    app_label = abstract_class.Meta.app_label
    model_name = abstract_class.__name__.replace('Abstract', '')

    if not is_model_registered(app_label, model_name):
        return type(str(model_name), (abstract_class, ), {'__module__': __name__, })
83293
def _get_bases(type_):
        # type: (type) -> Tuple[type, type]
        
        try:

            class _(type_):  # type: ignore
                """Check if type_ is subclassable."""

            BaseClass = type_
        except TypeError:
            BaseClass = object

        class MetaClass(_ValidationMeta, BaseClass.__class__):  # type: ignore
            """Use the type_ meta and include base validation functionality."""

        return BaseClass, MetaClass
561600
async def message_from_token(self, token: Text, payload: Any) \
            -> Optional[BaseMessage]:
        

        methods = [
            self._message_from_sr,
            self._message_from_token,
        ]

        for method in methods:
            msg = method(token, payload)

            if msg:
                return msg
1268736
async def root_message(self, msg, msg_type=None):
        
        await self.root()
        await self.message(msg, msg_type)
1248595
def _verified_message_type_from_id(message_type_id):
    # type: (int) -> ObjectType
    
    try:
        return ObjectType(message_type_id)
    except ValueError as error:
        raise NotSupportedError("Unsupported type {} discovered in data stream".format(message_type_id), error)
1340077
def log(self, msg):
        
        if self.master_class and self.instance_class:
            logger.info('{0} - {1} - {2} - {3} - lang: {4} msg: {5}'.format(
                self.ct_master.app_label, self.ct_master.model,
                self.instance_class, self.instance.language_code, self.instance.pk, msg)
            )
        elif self.instance_class:
            logger.info('{} - {}: {}'.format(self.instance_class, self.instance.pk, msg))
        else:
            logger.info('{}'.format(msg))
1313005
def toDict(self, msg: Dict) -> Dict:
        

        if isinstance(msg, Request):
            tmsg = msg.as_dict
        elif hasattr(msg, "_asdict"):
            tmsg = dict(msg._asdict())
        elif hasattr(msg, "__dict__"):
            tmsg = dict(msg.__dict__)
        elif self.allowDictOnly:
            raise ValueError("Message cannot be converted to an appropriate "
                             "format for transmission")
        else:
            tmsg = msg
        return tmsg
593873
def _cast_message(self, message=None):
        '''
        '''
        if message is None:
            message = {}
        if isinstance(message, Mapping):
            message = Message.load_message(message)
        return message.load_from(self.message, verify=True)
1044378
def handle(self, msg_type):
        

        def wrap(callback):
            self._handlers[msg_type] = callback
            return callback

        return wrap
799405
def create(self, **kwargs):
        

        response = self.ghost.execute_post('%s/' % self._type_name, json={
            self._type_name: [
                kwargs
            ]
        })

        return self._model_type(response.get(self._type_name)[0])
147894
async def load_message(self, msg_type, msg=None):
        
        msg = msg_type() if msg is None else msg
        fields = msg_type.f_specs() if msg_type else msg.__class__.f_specs()
        for field in fields:
            await self.message_field(msg, field)

        return msg
474212
async def ModelSet(self, config):
        '''
        
        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='Client',
                   request='ModelSet',
                   version=2,
                   params=_params)
        _params['config'] = config
        reply = await self.rpc(msg)
        return reply
75414
def process_message(message):
    
    message["type"] = message.pop("MsgType").lower()
    if message["type"] == 'event':
        message["type"] = str(message.pop("Event")).lower() + '_event'
        message_type = EventMetaClass.TYPES.get(message["type"], UnknownEvent)
    else:
        message_type = MessageMetaClass.TYPES.get(
            message["type"], UnknownMessage
        )
    return message_type(message)
505099
def message(self, message=None):
        
        if message is not None:
            self.response_model.message = message
        return self.response_model.message