2017-12-13 03:37:28 +01:00
|
|
|
import json
|
|
|
|
|
2017-12-17 16:15:44 +01:00
|
|
|
from platypush.message import Message
|
|
|
|
|
|
|
|
class Response(Message):
|
|
|
|
""" Response message class """
|
|
|
|
|
2017-12-18 03:09:38 +01:00
|
|
|
def __init__(self, target=None, origin=None, id=None, output=None, errors=[]):
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
Params:
|
|
|
|
target -- Target [String]
|
|
|
|
origin -- Origin [String]
|
|
|
|
output -- Output [String]
|
|
|
|
errors -- Errors [List of strings or exceptions]
|
2017-12-18 03:09:38 +01:00
|
|
|
id -- Message ID this response refers to
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
self.target = target
|
2017-12-13 03:37:28 +01:00
|
|
|
self.output = output
|
|
|
|
self.errors = errors
|
2017-12-17 16:15:44 +01:00
|
|
|
self.origin = origin
|
2017-12-18 03:09:38 +01:00
|
|
|
self.id = id
|
2017-12-13 03:37:28 +01:00
|
|
|
|
|
|
|
def is_error(self):
|
2017-12-17 16:15:44 +01:00
|
|
|
""" Returns True if the respopnse has errors """
|
2017-12-13 03:37:28 +01:00
|
|
|
return len(self.errors) != 0
|
|
|
|
|
2017-12-17 16:15:44 +01:00
|
|
|
@classmethod
|
|
|
|
def build(cls, msg):
|
|
|
|
msg = super().parse(msg)
|
|
|
|
args = {
|
|
|
|
'target' : msg['target'],
|
|
|
|
'output' : msg['response']['output'],
|
|
|
|
'errors' : msg['response']['errors'],
|
|
|
|
}
|
|
|
|
|
2017-12-18 03:09:38 +01:00
|
|
|
if 'id' in msg: args['id'] = msg['id']
|
2017-12-17 16:15:44 +01:00
|
|
|
if 'origin' in msg: args['origin'] = msg['origin']
|
|
|
|
return Response(**args)
|
|
|
|
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
"""
|
|
|
|
Overrides the str() operator and converts
|
|
|
|
the message into a UTF-8 JSON string
|
|
|
|
"""
|
|
|
|
|
|
|
|
return json.dumps({
|
2017-12-18 03:09:38 +01:00
|
|
|
'id' : self.id,
|
2017-12-17 16:15:44 +01:00
|
|
|
'type' : 'response',
|
|
|
|
'target' : self.target if hasattr(self, 'target') else None,
|
|
|
|
'origin' : self.origin if hasattr(self, 'origin') else None,
|
|
|
|
'response' : {
|
|
|
|
'output' : self.output,
|
|
|
|
'errors' : self.errors,
|
|
|
|
},
|
|
|
|
})
|
2017-12-13 03:37:28 +01:00
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|
|
|
|
|