diff options
author | Simo Sorce <simo@redhat.com> | 2015-04-16 16:44:51 -0400 |
---|---|---|
committer | Simo Sorce <simo@redhat.com> | 2015-04-20 16:07:14 -0400 |
commit | b9e31bf1cc44bdfeaf0454dadb578c4dbb8d588b (patch) | |
tree | 5abfb99f7669f49cdece5c3b15c632130aaf42f4 /custodia/message/formats.py | |
parent | f77b0158f87a13efc1d315b1bcb58cccf4406e88 (diff) | |
download | custodia-b9e31bf1cc44bdfeaf0454dadb578c4dbb8d588b.tar.gz custodia-b9e31bf1cc44bdfeaf0454dadb578c4dbb8d588b.tar.xz custodia-b9e31bf1cc44bdfeaf0454dadb578c4dbb8d588b.zip |
Move message parsing and validation
Create a message module to deal with message types and validation.
Signed-off-by: Simo Sorce <simo@redhat.com>
Diffstat (limited to 'custodia/message/formats.py')
-rw-r--r-- | custodia/message/formats.py | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/custodia/message/formats.py b/custodia/message/formats.py new file mode 100644 index 0000000..f8ddc69 --- /dev/null +++ b/custodia/message/formats.py @@ -0,0 +1,49 @@ +# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file + +from custodia.message.common import InvalidMessage +from custodia.message.common import UnknownMessageType +from custodia.message.common import UnallowedMessage +from custodia.message.simple import SimpleKey + + +default_types = ['simple'] + +key_types = {'simple': SimpleKey} + + +class Validator(object): + """Validates incoming messages.""" + + def __init__(self, allowed=None): + """Creates a Validator object. + + :param allowed: list of allowed message types (optional) + """ + self.allowed = allowed or default_types + self.types = dict() + for t in self.allowed: + self.types[t] = key_types[t] + + def add_types(self, types): + self.types.update(types) + + def parse(self, request, msg): + if not isinstance(msg, dict): + raise InvalidMessage('The message must be a dict') + + if 'type' not in msg: + raise InvalidMessage('The type is missing') + + if 'value' not in msg: + raise InvalidMessage('The value is missing') + + if msg['type'] not in list(self.types.keys()): + raise UnknownMessageType("Type '%s' is unknown" % msg['type']) + + if msg['type'] not in self.allowed: + raise UnallowedMessage("Message type '%s' not allowed" % ( + msg['type'],)) + + handler = self.types[msg['type']](request) + handler.parse(msg['value']) + return handler |