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 # 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
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 # how to display a call
57 # most of the time, we run 'forward'
58 if methodName=='forward':
59 try: action="forward(%s)"%args[0]['action']
60 except: action="forward(??)"
61 else: action=methodName
65 print "====> ManifoldAPI.%s"%repr(),"url",self.url
66 print "=> auth",self.auth
67 print "=> args",args,"kwds",kwds
69 'authentication': self.auth
71 args += (annotations,)
72 result=getattr(self.server, methodName)(*args, **kwds)
75 self._print_result(result)
76 print '<==== backend call %s returned'%(repr()),
78 return ResultValue(**result)
80 except Exception,error:
81 print "** MANIFOLD API ERROR **"
82 if "Connection refused" in error:
83 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
84 output="%s answered %s"%(self.url,error)))
87 print "===== xmlrpc catch-all exception:",error
89 traceback.print_exc(limit=3)
90 print "<==== ERROR On ManifoldAPI.%s"%repr()
91 raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE, output="%s"%error) )
95 def _execute_query(request, query, manifold_api_session_auth):
96 manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
101 result = manifold_api.forward(query.to_dict())
102 if result['code'] == 2:
103 raise Exception, 'Error running query: %r' % result
105 if result['code'] == 1:
107 print result['description']
110 #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}
112 return result['value']
114 def execute_query(request, query):
115 if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
116 raise Exception, "User not authenticated"
117 manifold_api_session_auth = request.session['manifold']['auth']
118 return _execute_query(request, query, manifold_api_session_auth)
120 def execute_admin_query(request, query):
122 admin_user, admin_password = config.manifold_admin_user_password()
123 admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
124 return _execute_query(request, query, admin_auth)