def _set_key(self, key, value, cast=None): if self.mimetype == MIMETYPE_JSON: if cast is not None: self.body[key] = cast(value) else: self.body[key] = value else: PARSER.warn('Attribute %s just available for MIME type %s' % (key, MIMETYPE_JSON))
def _get_key(self, key, default=None): if isinstance(default, dict): default = default.copy() if self.mimetype == MIMETYPE_JSON: if isinstance(default, dict): self.body.setdefault(key, default) return self.body.get(key, default) else: PARSER.info('Attribute %s just available for MIME type %s' % (key, MIMETYPE_JSON)) return default
def parse(self, msg): """Parses data and creates in case of a valid UMCP message the corresponding object. If the data contains more than the message the rest of the data is returned. :raises: :class:`.ParseError` """ header, nl, body = msg.partition('\n') # is the format of the header line valid? match = Message._header.match(header) if not match: if not nl: raise IncompleteMessageError( _('The message header is not (yet) complete')) PARSER.error('Error parsing UMCP message header: %r' % (header[:100], )) raise ParseError(UMCP_ERR_UNPARSABLE_HEADER, _('Unparsable message header')) groups = match.groupdict() self._type = groups[ 'type'] == 'REQUEST' and Message.REQUEST or Message.RESPONSE self._id = groups['id'] if 'mimetype' in groups and groups['mimetype']: self.mimetype = groups['mimetype'] self._id = groups['id'] try: self._length = int(groups['length']) except ValueError: PARSER.process('Invalid length information') raise ParseError(UMCP_ERR_UNPARSABLE_HEADER, _('Invalid length information')) self.command = groups['command'] if groups.get('arguments'): self.arguments = groups['arguments'].split(' ') # invalid/missing message body? current_length = len(body) if (not body and self._length) or self._length > current_length: PARSER.info('The message body is not complete: %d of %d bytes' % (current_length, self._length)) raise IncompleteMessageError( _('The message body is not (yet) complete')) remains = '' if len(body) > self._length: self.body, remains = body[:self._length], body[self._length:] else: self.body = body if self.mimetype == MIMETYPE_JSON: try: self.body = json.loads(self.body) if not isinstance(self.body, dict): raise ValueError('body is a %r' % (type(self.body).__name__, )) except ValueError as exc: self.body = {} PARSER.error('Error parsing UMCP message body: %s' % (exc, )) raise ParseError(UMCP_ERR_UNPARSABLE_BODY, _('error parsing UMCP message body')) PARSER.info('UMCP %(type)s %(id)s parsed successfully' % groups) return remains