Modified Query for list of authorities in Register page, temporary modified filter...
[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                 # XXX Connection refused for example
56                 print "** API ERROR **"
57                 import traceback
58                 traceback.print_exc()
59                 if debug: print "KO (unexpected exception)",error
60                 raise ManifoldException ( ManifoldResult (code=ManifoldCode.UNKNOWN_ERROR, output="%s"%error) )
61
62         return func
63
64 def execute_query(request, query):
65     if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
66         print "W: Used hardcoded demo account for execute_query"
67         manifold_api_session_auth = {'AuthMethod': 'password', 'Username': 'demo', 'AuthString': 'demo'}
68     else:
69         manifold_api_session_auth = request.session['manifold']['auth']
70     manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
71     print "-"*80
72     print query
73     print query.to_dict()
74     print "-"*80
75     result = manifold_api.forward(query.to_dict())
76     if result['code'] == 2:
77         raise Exception, 'Error running query'
78     return result['value']