added sticky notifications for warnings and errors + clean up code for v2 only
[myslice.git] / manifold / manifoldapi.py
1 # Manifold API Python interface
2 import xmlrpclib
3
4 from myslice.config import Config
5
6 from django.contrib import messages
7 from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException
8 from manifold.core.result_value import ResultValue
9
10 debug=False
11 debug=True
12
13 class ManifoldAPI:
14
15     def __init__(self, auth=None, cainfo=None):
16         
17         config = Config()
18         self.auth = auth
19         self.cainfo = cainfo
20         self.errors = []
21         self.trace = []
22         self.calls = {}
23         self.multicall = False
24         self.url = config.manifold_url
25         self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
26
27     def __repr__ (self): return "ManifoldAPI[%s]"%self.url
28
29     # a one-liner to give a hint of what the return value looks like
30     def _print_result (self, result):
31         if not result:                        print "[no/empty result]"
32         elif isinstance (result,str):         print "result is '%s'"%result
33         elif isinstance (result,list):        print "result is a %d-elts list"%len(result)
34         else:                                 print "[dont know how to display result]"
35
36     # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
37     # as of march 2013 we work with an API that essentially either returns the value, or raises 
38     # an xmlrpclib.Fault exception with always the same 8002 code
39     # since most of the time we're getting this kind of issues for expired sessions
40     # (looks like sessions are rather short-lived), for now the choice is to map these errors on 
41     # a SESSION_EXPIRED code
42     def __getattr__(self, methodName):
43         def func(*args, **kwds):
44             try:
45                 if debug: print "====> ManifoldAPI.%s"%methodName,"auth",self.auth,"args",args,"kwds",kwds
46                 result=getattr(self.server, methodName)(self.auth, *args, **kwds)
47                 if debug:
48                     print '<==== backend call %s(*%s,**%s) returned'%(methodName,args,kwds),
49                     print '.ctd. Authmethod=',self.auth['AuthMethod'], self.url,'->',
50                     self._print_result(result)
51
52                 return ResultValue(**result)
53
54             except Exception,error:
55                 if debug: print "KO (unexpected exception)",error
56                 raise ManifoldException ( ManifoldResult (code=ManifoldCode.UNKNOWN_ERROR, output="%s"%error) )
57
58         return func
59