AiC and REST login
[myslice.git] / manifoldapi / manifoldresult.py
1 # black magic to define enums
2 def enum(*sequential, **named):
3     enums = dict(zip(sequential, range(len(sequential))), **named)
4     return type('Enum', (), enums)
5
6 ManifoldCode = enum (
7     UNKNOWN_ERROR=-1,
8     SUCCESS=0,
9     SESSION_EXPIRED=1,
10     NOT_IMPLEMENTED=2,
11     SERVER_UNREACHABLE=3,
12 )
13
14 def truncate(result, length=50):
15     plain = "{}".format(result)
16     if len(plain) <= length-3:
17         return plain
18     else:
19         return plain[:(length-3)]+'...'
20
21 _messages_ = { -1 : "Unknown", 0: "OK", 1: "Session Expired", 2: "Not Implemented", 3: "Backend server unreachable"}
22
23 def truncate_result(result, length=50):
24     self = result
25     code = self['code']
26     result = "[MFresult {} (code={})".format(_messages_.get(code, "???"), code)
27     if code == 0:
28         value = self['value']
29         if isinstance(value, list):
30             result += " [value=list with {} elts]".format(len(value))
31         elif isinstance(value, dict):
32             result += " [value=dict with keys {}]".format(value.keys())
33         else:
34             result += " [value={}: {}]".format(type(value).__name__, value)
35     elif 'output' in self:
36         result += " [output={}]".format(self['output'])
37     else:
38         result += "<no output>"
39     result += "]"
40     return truncate(result, 60)
41
42 # being a dict this can be used with json.dumps
43 class ManifoldResult (dict):
44     def __init__ (self, code=ManifoldCode.SUCCESS, value=None, output=""):
45         self['code'] = code
46         self['value'] = value
47         self['output'] = output
48         self['description'] = '' # Jordan: needed by javascript code
49
50     def from_json (self, json_string):
51         d=json.dumps(json_string)
52         for k in ['code', 'value', 'output']:
53             self[k] = d[k]
54
55     # raw accessors
56     def code (self):
57         return self['code']
58     def output (self):
59         return self['output']
60
61     # this returns None if there's a problem, the value otherwise
62     def ok_value (self):
63         if self['code'] == ManifoldCode.SUCCESS:
64             return self['value']
65
66     # both data in a single string
67     def error (self):
68         return "code={} -- {}".format(self['code'], self['output'])
69     
70
71     def __repr__ (self):
72         return truncate_result(self, 60)
73
74 # probably simpler to use a single class and transport the whole result there
75 # instead of a clumsy set of derived classes 
76 class ManifoldException (Exception):
77     def __init__ (self, manifold_result):
78         self.manifold_result=manifold_result
79     def __repr__ (self):
80         return "<Manifold Exception {}>".format(self.manifold_result.error())