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 print "=> auth",self.auth
74 print "=> args",args,"kwds",kwds
76 'authentication': self.auth
78 args += (annotations,)
79 result=getattr(self.server, methodName)(*args, **kwds)
82 self._print_result(result)
83 print '<==== backend call %s returned'%(repr()),
85 return ResultValue(**result)
87 except Exception,error:
88 print "** MANIFOLD API ERROR **"
89 if "Connection refused" in error:
90 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
91 output="%s answered %s"%(self.url,error)))
94 print "===== xmlrpc catch-all exception:",error
96 traceback.print_exc(limit=3)
97 print "<==== ERROR On ManifoldAPI.%s"%repr()
98 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE, output="%s"%error) )
102 def _execute_query(request, query, manifold_api_session_auth):
103 manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
106 print query.to_dict()
108 result = manifold_api.forward(query.to_dict())
109 if result['code'] == 2:
110 raise Exception, 'Error running query: %r' % result
112 if result['code'] == 1:
114 print result['description']
117 #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}
119 return result['value']
121 def execute_query(request, query):
122 if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
123 raise Exception, "User not authenticated"
124 manifold_api_session_auth = request.session['manifold']['auth']
125 return _execute_query(request, query, manifold_api_session_auth)
127 def execute_admin_query(request, query):
129 admin_user, admin_password = config.manifold_admin_user_password()
130 admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
131 return _execute_query(request, query, admin_auth)