FIX: conflict in settings.py
[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 def mytruncate (obj, l):
14     # we will add '..' 
15     l1=l-2
16     repr="%s"%obj
17     return (repr[:l1]+'..') if len(repr)>l1 else repr
18
19 class ManifoldAPI:
20
21     def __init__(self, auth=None, cainfo=None):
22         
23         config = Config()
24         self.auth = auth
25         self.cainfo = cainfo
26         self.errors = []
27         self.trace = []
28         self.calls = {}
29         self.multicall = False
30         self.url = config.manifold_url
31         self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
32
33     def __repr__ (self): return "ManifoldAPI[%s]"%self.url
34
35     # a one-liner to give a hint of what the return value looks like
36     def _print_result (self, result):
37         if not result:                        print "[no/empty result]"
38         elif isinstance (result,str):         print "result is '%s'"%result
39         elif isinstance (result,list):        print "result is a %d-elts list"%len(result)
40         elif isinstance (result,dict):        
41             print "result is a dict with %d keys : %s"%(len(result),result.keys())
42             for (k,v) in result.iteritems(): 
43                 if v is None: continue
44                 print '+++',k,':',mytruncate (v,60)
45         else:                                 print "[dont know how to display result] %s"%result
46
47     # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
48     # as of march 2013 we work with an API that essentially either returns the value, or raises 
49     # an xmlrpclib.Fault exception with always the same 8002 code
50     # since most of the time we're getting this kind of issues for expired sessions
51     # (looks like sessions are rather short-lived), for now the choice is to map these errors on 
52     # a SESSION_EXPIRED code
53     def __getattr__(self, methodName):
54         def func(*args, **kwds):
55             try:
56                 if debug:
57                     print "====> ManifoldAPI.%s"%methodName,"auth",self.auth,"args",args,"kwds",kwds
58                 result=getattr(self.server, methodName)(self.auth, *args, **kwds)
59                 if debug:
60                     print '<==== backend call %s(*%s,**%s) returned'%(methodName,args,kwds),
61                     print '.ctd. Authmethod=',self.auth['AuthMethod'], self.url,'->',
62                     self._print_result(result)
63                     print '===== ManifoldAPI call done'
64
65                 return ResultValue(**result)
66
67             except Exception,error:
68                 # XXX Connection refused for example
69                 print "** API ERROR **"
70                 import traceback
71                 traceback.print_exc()
72                 if debug: print "KO (unexpected exception)",error
73                 raise ManifoldException ( ManifoldResult (code=ManifoldCode.UNKNOWN_ERROR, output="%s"%error) )
74
75         return func
76
77 def execute_query(request, query):
78     if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
79         print "W: Used hardcoded demo account for execute_query"
80         manifold_api_session_auth = {'AuthMethod': 'password', 'Username': 'demo', 'AuthString': 'demo'}
81     else:
82         manifold_api_session_auth = request.session['manifold']['auth']
83     manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
84     print "-"*80
85     print query
86     print query.to_dict()
87     print "-"*80
88     result = manifold_api.forward(query.to_dict())
89     if result['code'] == 2:
90         raise Exception, 'Error running query: %r' % result
91
92     # XXX Handle errors
93     #Error running query: {'origin': [0, 'XMLRPCAPI'], 'code': 2, 'description': 'No such session: No row was found for one()', 'traceback': 'Traceback (most recent call last):\n  File "/usr/local/lib/python2.7/dist-packages/manifold/core/xmlrpc_api.py", line 68, in xmlrpc_forward\n    user = Auth(auth).check()\n  File "/usr/local/lib/python2.7/dist-packages/manifold/auth/__init__.py", line 245, in check\n    return self.auth_method.check()\n  File "/usr/local/lib/python2.7/dist-packages/manifold/auth/__init__.py", line 95, in check\n    raise AuthenticationFailure, "No such session: %s" % e\nAuthenticationFailure: No such session: No row was found for one()\n', 'type': 2, 'ts': None, 'value': None}
94
95
96     return result['value']