Debian Codegraph @

mistral_lib/actions/types.py

raw
1 # Copyright 2014 - Mirantis, Inc.
2 # Copyright 2015 - StackStorm, Inc.
3 # Copyright 2016 - Brocade Communications Systems, Inc.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 from mistral_lib import serialization
18 from mistral_lib import utils
19
20
21 class Result(serialization.MistralSerializable):
22 """Action result."""
23
24 def __init__(self, data=None, error=None, cancel=False):
25 self.data = data
26 self.error = error
27 self.cancel = cancel
28
29 def __repr__(self):
30 return 'Result [data=%s, error=%s, cancel=%s]' % (
31 repr(self.data), repr(self.error), str(self.cancel)
32 )
33
34 def cut_repr(self):
35 _data = utils.mask_data(self.data)
36 _error = utils.mask_data(self.error)
37 _cancel = utils.mask_data(self.cancel)
38
39 return 'Result [data=%s, error=%s, cancel=%s]' % (
40 utils.cut(_data), utils.cut(_error), str(_cancel)
41 )
42
43 def is_cancel(self):
44 return self.cancel
45
46 def is_error(self):
47 return self.error is not None and not self.is_cancel()
48
49 def is_success(self):
50 return not self.is_error() and not self.is_cancel()
51
52 def __eq__(self, other):
53 return (
54 self.data == other.data and
55 self.error == other.error and
56 self.cancel == other.cancel
57 )
58
59 def __ne__(self, other):
60 return not self.__eq__(other)
61
62 def to_dict(self):
63 return {'result': self.data if self.is_success() else self.error}
64
65
66 class ResultSerializer(serialization.DictBasedSerializer):
67 def serialize_to_dict(self, entity):
68 return {
69 'data': entity.data,
70 'error': entity.error,
71 'cancel': entity.cancel
72 }
73
74 def deserialize_from_dict(self, entity_dict):
75 return Result(
76 entity_dict['data'],
77 entity_dict['error'],
78 entity_dict.get('cancel', False)
79 )
80
81
82 serialization.register_serializer(Result, ResultSerializer())