1 # Manifold API Python interface
4 from myslice.config import Config
6 from django.contrib import messages
7 from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException
8 from manifold.core.result_value import ResultValue
13 def mytruncate (obj, l):
17 return (repr[:l1]+'..') if len(repr)>l1 else repr
21 def __init__(self, auth=None, cainfo=None):
28 self.multicall = False
30 self.url = config.manifold_url()
31 self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
33 def __repr__ (self): return "ManifoldAPI[%s]"%self.url
35 def _print_value (self, value):
37 if isinstance (value,list): print "[%d]"%len(value),
38 elif isinstance (value,dict): print "{%d}"%len(value),
39 print mytruncate (value,80)
41 # a one-liner to give a hint of what the return value looks like
42 def _print_result (self, result):
43 if not result: print "[no/empty result]"
44 elif isinstance (result,str): print "result is '%s'"%result
45 elif isinstance (result,list): print "result is a %d-elts list"%len(result)
46 elif isinstance (result,dict):
47 print "result is a dict with %d keys : %s"%(len(result),result.keys())
48 for (k,v) in result.iteritems():
49 if v is None: continue
50 if k=='value': self._print_value(v)
51 else: print '+++',k,':',mytruncate (v,30)
52 else: print "[dont know how to display result] %s"%result
54 # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
55 # as of march 2013 we work with an API that essentially either returns the value, or raises
56 # an xmlrpclib.Fault exception with always the same 8002 code
57 # since most of the time we're getting this kind of issues for expired sessions
58 # (looks like sessions are rather short-lived), for now the choice is to map these errors on
59 # a SESSION_EXPIRED code
60 def __getattr__(self, methodName):
61 def func(*args, **kwds):
62 # how to display a call
64 # most of the time, we run 'forward'
65 if methodName=='forward':
66 try: action="forward(%s)"%args[0]['action']
67 except: action="forward(??)"
68 else: action=methodName
72 print "====> ManifoldAPI.%s"%repr(),"url",self.url
73 # No password in the logs
74 logAuth = copy.copy(self.auth)
75 for obfuscate in ['Authring','session']:
76 if obfuscate in logAuth: logAuth[obfuscate]="XXX"
77 print "=> auth",logAuth
78 print "=> args",args,"kwds",kwds
80 'authentication': self.auth
82 args += (annotations,)
83 result=getattr(self.server, methodName)(*args, **kwds)
84 print "%s%r" %(methodName, args)
88 self._print_result(result)
89 print '<==== backend call %s returned'%(repr()),
91 return ResultValue(**result)
93 except Exception,error:
94 print "** MANIFOLD API ERROR **"
96 print "===== xmlrpc catch-all exception:",error
98 traceback.print_exc(limit=3)
99 if "Connection refused" in error:
100 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
101 output="%s answered %s"%(self.url,error)))
103 print "<==== ERROR On ManifoldAPI.%s"%repr()
104 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE, output="%s"%error) )
108 def _execute_query(request, query, manifold_api_session_auth):
109 manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
112 print query.to_dict()
114 result = manifold_api.forward(query.to_dict())
115 if result['code'] == 2:
116 raise Exception, 'Error running query: %r' % result
118 if result['code'] == 1:
120 print result['description']
123 #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}
125 return result['value']
127 def execute_query(request, query):
128 if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
129 raise Exception, "User not authenticated"
130 manifold_api_session_auth = request.session['manifold']['auth']
131 return _execute_query(request, query, manifold_api_session_auth)
133 def execute_admin_query(request, query):
135 admin_user, admin_password = config.manifold_admin_user_password()
136 admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
137 return _execute_query(request, query, admin_auth)