def respondToPost(self, transaction): """Respond to a Post request. This is similar to the xmlrpcserver.py example from the xmlrpc library distribution, only it's been adapted to work within a WebKit servlet. """ try: # get arguments data = transaction.request().rawInput(rewind=1).read() encoding = _getXmlDeclAttr(data, "encoding") params, method = xmlrpclib.loads(data) # generate response try: # This first test helps us to support PythonWin, which uses # repeated calls to __methods__.__getitem__ to determine the # allowed methods of an object. if method == "__methods__.__getitem__": response = self.exposedMethods()[params[0]] else: response = self.call(method, *params) if not isinstance(response, tuple): response = (response,) except xmlrpclib.Fault, fault: response = xmlrpclib.dumps(fault, encoding=encoding, allow_none=self.allow_none) self.sendOK("text/xml", response, transaction) self.handleException(transaction) except Exception, e: fault = self.resultForException(e, transaction) response = xmlrpclib.dumps(xmlrpclib.Fault(1, fault), encoding=encoding, allow_none=self.allow_none) self.sendOK("text/xml", response, transaction) self.handleException(transaction)
def _marshaled_dispatch(self, data, dispatch_method = None, path = None): try: params, method = xmlrpclib.loads(data) # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except: # report low level exception back to server # (each dispatcher should have handled their own # exceptions) exc_type, exc_value, tb = sys.exc_info() while tb.tb_next is not None: tb = tb.tb_next # find last frame of the traceback lineno = tb.tb_lineno code = tb.tb_frame.f_code filename = code.co_filename name = code.co_name response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s FILENAME: %s LINE: %s NAME: %s" % ( exc_type, exc_value, filename, lineno, name)), encoding=self.encoding, allow_none=self.allow_none) return response
def process(self): """ Processes the xmlrpc request. """ response = self._request.getResponse() # XML-RPC starts here try: # Get parameters params, method = xmlrpclib.loads(self._data) params = list(params) params.insert(0, self._request) params = tuple(params) try: # Call the method result = self.xmlrpcCall(method, params) if type(result) != type (()): result = (result,) except xmlrpclib.Fault, faultobj: # Throw an xmlrpc exception result = xmlrpclib.dumps(faultobj) except: # Format other exceptions into xmlrpc faults result = xmlrpclib.dumps(xmlrpclib.Fault(1, '%s:%s' % (sys.exc_type, sys.exc_value))) else: # Passed. result = xmlrpclib.dumps(result, methodresponse=1)
def _marshaled_dispatch(self, data, dispatch_method = None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the prefered means of changing method dispatch behavior. """ params, method = xmlrpclib.loads(data) # generate response try: if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=1) except Fault, fault: response = xmlrpclib.dumps(fault)
def dispatch(self, data, **kwargs): """ Extracts the xml marshaled parameters and method name and calls the underlying method and returns either an xml marshaled response or an XMLRPC fault Although very similar to the superclass' _marshaled_dispatch, this method has a different name due to the different parameters it takes from the superclass method. """ try: params, method = xmlrpc.xmlrpc_client.loads(data) try: response = self._dispatch(method, params, **kwargs) except TypeError: # Catch unexpected keyword argument error response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Fault as fault: response = dumps(fault, allow_none=self.allow_none, encoding=self.encoding) except Exception: response = dumps( Fault(1, 'Unknown error'), encoding=self.encoding, allow_none=self.allow_none, ) return response
def execute (self, request=sys.stdin, response=sys.stdout, meta=None): """processes a request and dispatches the call""" if not meta: meta = {} meta['xmlrpcserver'] = self params = method = result = None try: params, rpccall = xmlrpclib.loads(request.read()) except: response.write( xmlrpclib.dumps(xmlrpclib.Fault (-32000, self.systemerrors[-32000]), methodresponse = True)) return try: result = self.resolve(rpccall)(meta, *params) response.write( xmlrpclib.dumps((result,), methodresponse = True, allow_none=True)) except xmlrpclib.Fault, fault: response.write( xmlrpclib.dumps(fault, methodresponse = True))
def run(driver, driver_info): """Convenience method to run command on the given driver""" cmd = SRCommand(driver_info) try: cmd.parse() cmd.run_statics() sr = driver(cmd, cmd.sr_uuid) sr.direct = True ret = cmd.run(sr) if ret == None: print util.return_nil () else: print ret except (Exception, SR.SRException) as e: try: util.logException(driver_info['name']) except KeyError: util.SMlog('driver_info does not contain a \'name\' key.') except: pass # If exception is of type SR.SRException, pass to Xapi. # If generic python Exception, print a generic xmlrpclib # dump and pass to XAPI. if isinstance(e, SR.SRException): print e.toxml() else: print xmlrpclib.dumps(xmlrpclib.Fault(1200, str(e)), "", True) sys.exit(0)
def _system_methodSignature(self, *p, **kw): try: method = self._find_method(p[0]) rpcresponse = xmlrpclib.dumps((method.signatures,), methodresponse=1) except: rpcresponse = xmlrpclib.dumps(('Invalid method',), methodresponse=1) return rpcresponse
def setResult(self, result): """Sets the result of the response Sets the return body equal to the (string) argument "body". Also updates the "content-length" return header. If the body is a 2-element tuple, then it will be treated as (title,body) If is_error is true then the HTML will be formatted as a Zope error message instead of a generic HTML page. """ body = premarshal(result) if isinstance(body, xmlrpclib.Fault): # Convert Fault object to XML-RPC response. body = xmlrpclib.dumps(body, methodresponse=True) else: # Marshall our body as an XML-RPC response. Strings will be sent # as strings, integers as integers, etc. We do *not* convert # everything to a string first. try: body = xmlrpclib.dumps((body,), methodresponse=True, allow_none=True) except: # We really want to catch all exceptions at this point! self.handleException(sys.exc_info()) return super(XMLRPCResponse, self).setResult( DirectResult((body,), [('content-type', 'text/xml;charset=utf-8'), ('content-length', str(len(body)))]) )
def _marshaled_dispatch(self, data, dispatch_method = None): params, method = xmlrpclib.loads(data) try: if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # With either Unicode or normal strings, we can only transmit # \t, \n, \r, \u0020-\ud7ff, \ue000-\ufffd, and \u10000-\u10ffff # in an XML document. xmlrpclib does not escape these values # properly, and then breaks when it comes to parse the document. # To hack around this problem, we use repr here and exec above # to transmit the string using Python encoding. # Thanks to David Mertz <*****@*****.**> for the trick (buried # in xml_pickle.py). if (isinstance(response, types.StringType) or isinstance(response, unicode)): response = repr(response)[1:-1] response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=1) except xmlrpclib.Fault, fault: response = xmlrpclib.dumps(fault)
def test_kwargs(self): xml = dumps((1, 2), 'kwargstest') ret = self.dispatcher.dispatch(xml) out, name = loads(ret) self.assertFalse(out[0]) ret = self.dispatcher.dispatch(xml, c=1) out, name = loads(ret) self.assertTrue(out[0]) xml = dumps((1,),'requestargtest') ret = self.dispatcher.dispatch(xml, request=True) out, name = loads(ret) self.assertTrue(out[0]) xml = """<?xml version='1.0'?> <methodCall> <methodName>withoutargstest</methodName> <params> </params> </methodCall> """ ret = self.dispatcher.dispatch(xml, request='fakerequest') out, name = loads(ret) self.assertTrue(out[0])
def RPC_handler(self, data): "Handler for incoming remote procedure calls" try: if self.stage == XMLRPC_STAGE_ZERO: self.stage = XMLRPC_STAGE_ONE # Get client's headers out of the buffer elif self.stage == XMLRPC_STAGE_ONE: self.stage = XMLRPC_STAGE_TWO params, method = xmlrpclib.loads(data) if isinstance(params[0], type({})): aside = params[0] aside['_socket'] = self._sock aside['_socket_info'] = (self.host, self.port) params = (aside,) result = self.rpc_dispatch(method, params) if getattr(result, 'faultCode', None) is not None: response = xmlrpclib.dumps(result) else: response = xmlrpclib.dumps(result, methodresponse=1) except: response = xmlrpclib.dumps(xmlrpclib.Fault(1, "Socker(tm): %s" % traceback.format_exc())) if self.stage == XMLRPC_STAGE_TWO: final_output = ["HTTP/1.1 200 OK", "Server: BlueBridge Socker(tm)", "Content-Length: %i" % len(response), "Connection: close", "Content-Type: text/xml", "", response] self.send('\n'.join(final_output)) self.terminate()
def call(request): """ This is the view you need to map into your URL space to process RPC calls. """ if request.POST: p, u = xmlrpclib.getparser() p.feed(request.raw_post_data) p.close() #print request.raw_post_data args = u.close() method = u.getmethodname() func = getattr(__import__('blog'), 'metaweblogapi') func = getattr(func,str(method.split('.')[1])) if DEBUG: print method, func, args if func is not None: try: result = func(*args) xml = xmlrpclib.dumps((result,), methodresponse=1) if DEBUG: print result except Exception, e: if DEBUG: print e xml = xmlrpclib.dumps(xmlrpclib.Fault(-32400, 'system error: %s' % e), methodresponse=1) else: xml = xmlrpclib.dumps(xmlrpclib.Fault(-32601, 'method unknown: %s' % method), methodresponse=1) return HttpResponse(xml, mimetype='text/xml; charset=utf-8')
def send_rpc_error(self, req, e): """Send an XML-RPC fault message back to the caller""" rpcreq = req.rpc fault = None if isinstance(e, ProtocolException): fault = e._exc elif isinstance(e, ServiceException): e = e._exc elif isinstance(e, MethodNotFound): fault = xmlrpclib.Fault(-32601, to_unicode(e)) elif isinstance(e, PermissionError): fault = xmlrpclib.Fault(403, to_unicode(e)) elif isinstance(e, ResourceNotFound): fault = xmlrpclib.Fault(404, to_unicode(e)) if fault is not None : self._send_response(req, xmlrpclib.dumps(fault), rpcreq['mimetype']) else : self.log.error(e) import traceback from tracrpc.util import StringIO out = StringIO() traceback.print_exc(file = out) self.log.error(out.getvalue()) err_code = hasattr(e, 'code') and e.code or 1 method = rpcreq.get('method') self._send_response(req, xmlrpclib.dumps( xmlrpclib.Fault(err_code, "'%s' while executing '%s()'" % (str(e), method))))
def do_POST(self): # Simplified version of SimpleXMLRPCRequestHandler.do_POST l = int(self.headers["Content-Length"]) request_txt = self.rfile.read(l) params, func = xmlrpclib.loads(request_txt) if self.path not in peers: self.send_response(404) self.end_headers() return self.send_response(200) self.end_headers() peer = peers[self.path] try: if not hasattr(peer, func): raise "No such method" result = getattr(peer, func)(*params) response = xmlrpclib.dumps((result,)) except: exc_type, exc_value, exc_tb = sys.exc_info() response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)), ) # need to call a function with (*params) self.wfile.write(response)
def test_serialize_request(methodname, *args): for arg in args: try: xmlrpclib.dumps((arg,), methodresponse=True, methodname=methodname) except Exception as e: print "Could not serialize arg %s" % str(arg) raise e
def continue_request (self, data, request): params, method = xmlrpclib.loads (data) try: # generate response try: response = self.call (method, params) #if type(response) == type(()): response = (response,) except: # report exception back to server response = xmlrpclib.dumps ( xmlrpclib.Fault (1, "%s:%s" % (sys.exc_type, sys.exc_value)) ) else: response = xmlrpclib.dumps (response, methodresponse=1) except: import traceback traceback.print_exc() # internal error, report as HTTP server error request.error (500) else: # got a valid XML RPC response request['Content-Type'] = 'text/xml' request.push (response) request.done()
def test_normal(self): from pyramid_xmlrpc import XMLRPCView class Test(XMLRPCView): def a_method(self, param): return param # set up a request param = 'what' import xmlrpclib packet = xmlrpclib.dumps((param,), methodname='a_method') request = testing.DummyRequest() request.body = packet request.content_length = len(packet) # instantiate the view context = testing.DummyModel() instance = Test(context, request) # these are fair game for the methods to use if they want self.failUnless(instance.context is context) self.failUnless(instance.request is request) # exercise it response = instance() self.assertEqual(response.body, xmlrpclib.dumps((param,), methodresponse=True))
def dispatch(self, data, **kwargs): """ Extracts the xml marshaled parameters and method name and calls the underlying method and returns either an xml marshaled response or an XMLRPC fault Although very similar to the superclass' _marshaled_dispatch, this method has a different name due to the different parameters it takes from the superclass method. """ try: params, method = xmlrpclib.loads(data) try: response = self._dispatch(method, params, **kwargs) except TypeError as e: # XXX: Hack! if "unexpected keyword" in "%s" % e: # Catch unexpected keyword argument error response = self._dispatch(method, params) else: raise # wrap response in a singleton tuple response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Fault, fault: logger.warn("Got fault when processing method %s" % method) traceback.print_exc() response = xmlrpclib.dumps(fault, allow_none=self.allow_none, encoding=self.encoding)
def do_POST(s): s.do_HEAD() clen = int( s.headers.getheader( "content-length" ) ) body = s.rfile.read( clen ) d = cgi.parse_qs( body ) try: uli_string = d.get( "ULI", d.get( "uli", d.get( "Uli", [None] )))[0] except KEYERROR: uli_string = None try: (args,func_name) = xmlrpclib.loads( body ) if func_name == "uli": uli_result = s.server.dingding.uli.uli( args[0] ) s.wfile.write( xmlrpclib.dumps( (uli_result,) ) ) return s.wfile.write( xmlrpclib.dumps( (1,) ) ) # auto response, for now if func_name == "subscribe": s.handle_xmlrpc_subscribe( *args ) elif func_name == "unsubscribe": s.handle_xmlrpc_unsubscribe( *args ) except ExpatError: pass if uli_string != None: s.wfile.write( s.server.dingding.uli.uli( uli_string ) ) return
def Dispatch(req, method, args): # Default configuration defcfg = {'xmlrpc_server': { 'datadir': '/var/lib/rteval', 'db_server': 'localhost', 'db_port': 5432, 'database': 'rteval', 'db_username': '******', 'db_password': '******' } } # Fetch configuration cfg = rtevalConfig(defcfg) cfg.Load(append=True) # Prepare an object for executing the query xmlrpc = XMLRPC_API1(config=cfg.GetSection('xmlrpc_server')) # Exectute it result = xmlrpc.Dispatch(method, args) # Send the result if type(result) == types.TupleType: req.write(dumps(result, None, methodresponse=1)) else: req.write(dumps((result,), None, methodresponse=1))
def test_xml_loads(): """ Test the `ipalib.rpc.xml_loads` function. """ f = rpc.xml_loads params = (binary_bytes, utf8_bytes, unicode_str, None) wrapped = rpc.xml_wrap(params, API_VERSION) # Test un-serializing an RPC request: data = dumps(wrapped, b'the_method', allow_none=True) (p, m) = f(data) assert_equal(m, u'the_method') assert_equal(p, params) # Test un-serializing an RPC response: data = dumps((wrapped,), methodresponse=True, allow_none=True) (tup, m) = f(data) assert m is None assert len(tup) == 1 assert type(tup) is tuple assert_equal(tup[0], params) # Test un-serializing an RPC response containing a Fault: for error in (unicode_str, u'hello'): fault = Fault(69, error) data = dumps(fault, methodresponse=True, allow_none=True, encoding='UTF-8') e = raises(Fault, f, data) assert e.faultCode == 69 assert_equal(e.faultString, error) assert type(e.faultString) is unicode
def test_normal(self): def unwrapped(context, what): return what wrapped = self._callFUT(unwrapped) self.assertEqual(wrapped.__name__, 'unwrapped') self.assertEqual(wrapped.__grok_module__, unwrapped.__module__) context = testing.DummyModel() request = testing.DummyRequest() param = 'what' if PY3: import xmlrpc.client packet = xmlrpc.client.dumps((param,), methodname='__call__') else: import xmlrpclib packet = xmlrpclib.dumps((param,), methodname='__call__') request = testing.DummyRequest() request.body = packet request.content_length = len(packet) response = wrapped(context, request) if PY3: self.assertEqual(response.body, bytes(xmlrpc.client.dumps((param,), methodresponse=True), encoding='utf-8')) else: self.assertEqual(response.body, xmlrpclib.dumps((param,), methodresponse=True))
def xmlrpc(): if request.method == 'GET': return render_template('xmlrpc-methods.html', methods = current_app.wl_server_methods) raw_data = request.get_data() params, method_name = xmlrpclib.loads(raw_data) if method_name.startswith('Util.'): method_name = method_name[len('Util.'):] if method_name not in current_app.wl_server_methods: return xmlrpclib.dumps(xmlrpclib.Fault("Method not found", "Method not found")) try: if method_name == 'test_me': result = params[0] else: method = getattr(current_app.wl_server_instance, 'do_%s' % method_name) result = method(*params) except: exc_type, exc_instance, _ = sys.exc_info() remote_exc_type = _get_type_name(exc_type) fault = xmlrpclib.Fault(remote_exc_type, repr(exc_instance.args)) log.error(__name__, 'Error on %s' % method_name) log.error_exc(__name__) return xmlrpclib.dumps(fault) return xmlrpclib.dumps( (result,))
def do_POST(self): try: # get arguments data = self.rfile.read(int(self.headers["content-length"])) params, method = xmlrpclib.loads(data) if debug: print "method:", repr(method) print "params:", repr(params) # generate response try: response = self.call(method, params) if debug: print 'call response: %r' % response if type(response) != type(()): response = (response,) except: # report exception back to server response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value))) else: response = xmlrpclib.dumps(response, methodresponse=1) except Exception, e: # internal error, report as HTTP server error self.send_response(500) self.end_headers()
def do_POST(self): try: # get arguments data = self.rfile.read(int(self.headers["content-length"])) params, method = xmlrpclib.loads(data) # generate response try: response = self.call(method, params) # wrap response in a singleton tuple response = (response,) except: # report exception back to server response = xmlrpclib.dumps(xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2])) else: response = xmlrpclib.dumps(response, methodresponse=1) except: # internal error, report as HTTP server error self.send_response(500) self.end_headers() else: # got a valid XML RPC response self.send_response(200) self.send_header("Content-type", "text/xml") self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response) # shut down the connection (from Skip Montanaro) self.wfile.flush() self.connection.shutdown(1)
def handle_request(self): ##TODO: Need more error handling! size_buf = self.inpipe.read(isz) size = struct.unpack('I',size_buf)[0] call_xml = self.inpipe.read(size) self.outpipe.write(struct.pack('c','M')) name='' try: args,name = xmlrpclib.loads(call_xml) result = self.__call__(name, *args) result=(result,) #response must always be a length 1 tuple except: import traceback result ='Error running call '+name+'\n'+call_xml+'\n' result += '\n'.join(traceback.format_exception(*sys.exc_info())) result = (result,) try: res_xml = bytes(xmlrpclib.dumps(result, methodresponse=True)) except: import traceback res_xml = bytes(xmlrpclib.dumps('Method result of length %i could not be converted to XML'%(len(res_xml)), methodresponse=True)) size = len(res_xml) self.outpipe.write(struct.pack('I',size)) self.outpipe.write(res_xml) self.outpipe.flush()
def test_xmlrpc_marshal(self): from supervisor import xmlrpc data = xmlrpc.xmlrpc_marshal(1) self.assertEqual(data, xmlrpclib.dumps((1,), methodresponse=True)) fault = xmlrpclib.Fault(1, 'foo') data = xmlrpc.xmlrpc_marshal(fault) self.assertEqual(data, xmlrpclib.dumps(fault))
def _marshaled_dispatch(self, data, dispatch_method=None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the prefered means of changing method dispatch behavior. """ try: params, method = xmlrpclib.loads(data) # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Exception: # report exception back to server exc_type, exc_value, exc_tb = sys.exc_info() response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none, ) return response
def main(request): params, method = xmlrpclib.loads(request.data) try: fn = eval(method) except: fn = None result = xmlrpclib.Fault(1, "Function '%s' not found" % method) response = xmlrpclib.dumps(result) if fn: try: result = fn(request, *params) if result == None: result = "" response = xmlrpclib.dumps((result,), methodresponse=1) except: result = xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)) response = xmlrpclib.dumps(result) raise request.send_response(200) request.send_header("Content-type", "text/xml") request.send_header("Content-length", str(len(response))) request.end_headers() request.wfile.write(response)
def __request(self, methodname, params): # call a method on the remote server request = xmlrpclib.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none) response = self.__transport.request(self.__host, self.__handler, request, verbose=self.__verbose) if len(response) == 1: response = response[0] return response
def call_xmlrpc(self, method_name, *method_params): payload = xmlrpclib.dumps((method_params), method_name) response = requests.request( 'POST', self.xmlrpc_url, data=payload, headers={'Content-Type': 'application/xml'}, auth=(self.username, self.password), timeout=100, stream=False) if response.status_code == 200: result = xmlrpclib.loads(response.content)[0][0] return result else: raise LavaServerException(response.status_code)
def request_encoding(data, method, encoding=None): r""" Test http request marshalling >>> request_encoding(unicode("abc", "ascii"), "test", "iso-8859-1") (((u'abc',), 'test'), (('abc',), 'test')) >>> request_encoding(unicode("едц", "iso-8859-1"), "test", "iso-8859-1") (((u'\xe5\xe4\xf6',), 'test'), ((u'\xe5\xe4\xf6',), 'test')) >>> request_encoding(unicode("едц", "iso-8859-1"), "test") (((u'\xe5\xe4\xf6',), 'test'), ((u'\xe5\xe4\xf6',), 'test')) """ if not isinstance(data, type(())): data = (data,) body = xmlrpclib.dumps(data, method, encoding=encoding) return (data, method), xmlrpclib.loads(body)
def cryptolog_get_transaction_info(cls, attachments): attachment, = attachments url = config.get(CONFIG_SECTION, 'url') assert url verify = True if config.get(CONFIG_SECTION, 'no_verify') == '1': verify = False method = 'requester.getTransactionInfo' headers = cls.cryptolog_headers() auth = cls.cryptolog_basic_auth() data = xmlrpclib.dumps((attachment.cryptolog_id,), method) req = requests.post(url, headers=headers, auth=auth, data=data, verify=verify) response, _ = xmlrpclib.loads(req.content) attachment.append_log(method, response) attachment.cryptolog_status = response[0]['status'] attachment.save()
def xmlrpc_return(start_response, service, method, params, legacy_exceptions=False): """ Helper to call a service's method with some params, using a wsgi-supplied ``start_response`` callback. This is the place to look at to see the mapping between core exceptions and XML-RPC fault codes. """ # Map OpenERP core exceptions to XML-RPC fault codes. Specific exceptions # defined in ``openerp.exceptions`` are mapped to specific fault codes; # all the other exceptions are mapped to the generic # RPC_FAULT_CODE_APPLICATION_ERROR value. # This also mimics SimpleXMLRPCDispatcher._marshaled_dispatch() for # exception handling. try: def fix(res): """ This fix is a minor hook to avoid xmlrpclib to raise TypeError exception: - To respect the XML-RPC protocol, all "int" and "float" keys must be cast to string to avoid TypeError, "dictionary key must be string" - And since "allow_none" is disabled, we replace all None values with a False boolean to avoid TypeError, "cannot marshal None unless allow_none is enabled" """ if res is None: return False elif type(res) == dict: return dict( (str(key), fix(value)) for key, value in res.items()) else: return res result = fix(openerp.netsvc.dispatch_rpc(service, method, params)) response = xmlrpclib.dumps((result, ), methodresponse=1, allow_none=False, encoding=None) except Exception, e: if legacy_exceptions: response = xmlrpc_handle_exception_legacy(e) else: response = xmlrpc_handle_exception(e)
def call(self, method, args, responseCallback, errorCallback): """ Public method to call the remote server. @param method name of the remote method to be called (string) @param args tuple of method arguments (tuple) @param responseCallback method to be called with the returned result as a tuple (function) @param errorCallback method to be called in case of an error with error code and error string (function) """ assert isinstance(args, tuple), \ "argument must be tuple or Fault instance" data = xmlrpc.dumps(args, method).encode("utf-8") reply = self.__networkManager.post(self.__request, QByteArray(data)) self.__callmap[reply] = (responseCallback, errorCallback)
def modify_project_membership (url, root_bundle, cert, key, cred_strings, project_urn, add = None, remove = None, change = None): options = {} if add: to_add = [] for urn,role in add: to_add.append({"PROJECT_MEMBER" : urn, "PROJECT_ROLE" : role}) options["members_to_add"] = to_add if remove: options["members_to_remove"] = remove if change: to_change = [] for urn,role in change: to_change.append({"PROJECT_MEMBER" : urn, "PROJECT_ROLE" : role}) options["members_to_change"] = to_change req_data = xmlrpclib.dumps(("PROJECT", project_urn, cred_strings, options), methodname = "modify_membership") return _rpcpost(url, req_data, (cert, key), root_bundle)
def __call__(self, webui_obj): webui_obj.handler.send_response(200, 'OK') webui_obj.handler.send_header('Content-type', 'text/xml') webui_obj.handler.send_header('charset', 'UTF-8') webui_obj.handler.end_headers() try: length = int(webui_obj.env['CONTENT_LENGTH']) assert length < 10 * 1024 * 1024, 'request content way too big' data = webui_obj.handler.rfile.read(length) # This should be thread-safe, as the store is really a singleton self.store = webui_obj.store except Exception, e: # report as a fault to caller rather than propogating up to generic # exception handler response = xmlrpclib.dumps(xmlrpclib.Fault(1, repr(e)), encoding=self.encoding, allow_none=self.allow_none)
def saveFile(self, path): if self.controls.sndPath != "": status, sndpath = self.checkForMixedSound() if not status: return if sndpath != "": self.controls.sndPath = sndpath self.currentFile = path self.currentPath = os.path.split(path)[0] saveDict = self.getState() msg = xmlrpclib.dumps((saveDict, ), allow_none=True) f = open(path, 'w') f.write(msg) f.close() self.SetTitle('%s %s - %s' % (NAME, SG_VERSION, os.path.split(self.currentFile)[1])) self.is_unsaved = False
def __request (self, methodname, params): tuple_params = tuple([params[0]]) if sys.version_info.major == 3: requestContent = xmlrpc.client.dumps(tuple_params, methodname) else: requestContent = xmlrpclib.dumps(tuple_params, methodname) if(self.debug == True): print(("Anfrage: "+str(requestContent).replace("\n", ""))) headers = { 'User-Agent' : 'DomRobot/'+self.version+' Python-v2.7', 'Content-Type': 'text/xml','content-length': str(len(requestContent))} if(self.cookie!=None): headers['Cookie'] = self.cookie if sys.version_info.major == 3: req = urllib.request.Request(self.url, bytearray(requestContent, 'ascii'), headers) response = urllib.request.urlopen(req) else: req = urllib2.Request(self.url, bytearray(requestContent, 'ascii'), headers) response = urllib2.urlopen(req) responseContent = response.read() if sys.version_info.major == 3: cookies = response.getheader('Set-Cookie') else: cookies = response.info().getheader('Set-Cookie') if(self.debug == True): print(("Antwort: "+str(responseContent).replace("\n", ""))) if sys.version_info.major == 3: apiReturn = xmlrpc.client.loads(responseContent) else: apiReturn = xmlrpclib.loads(responseContent) apiReturn = apiReturn[0][0] if(apiReturn["code"]!=1000): raise NameError('There was a problem: %s (Error code %s)' % (apiReturn['msg'], apiReturn['code']), apiReturn) return False if(cookies!=None): if sys.version_info.major == 3: cookies = response.getheader('Set-Cookie') else: cookies = response.info().getheader('Set-Cookie') self.cookie = cookies if(self.debug == True): print(("Cookie:" + self.cookie)) return apiReturn
def addFeedback( self, stationId, musicId, likeFlag ): reqUrl = BASE_URL_LID %( self.rid, self.lid, "addFeedback" ) matchingSeed = "" userSeed = "" focusTraitId = "" args = ( self._timestamp(), self.authToken, stationId, musicId, matchingSeed, userSeed, focusTraitId, "", likeFlag, False ) req = xmlrpclib.dumps( args, "station.addFeedback" ) req = req.replace( "\n", "" ) enc = crypt.encryptString( req, self.keys['out'] ) u = urllib2.urlopen( reqUrl, enc ) resp = u.read() u.close()
def wsgi_xmlrpc_1(environ, start_response): """ The main PengERP WSGI handler.""" if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'].startswith( XML_RPC_PATH_1): length = int(environ['CONTENT_LENGTH']) data = environ['wsgi.input'].read(length) params, method = xmlrpclib.loads(data) path = environ['PATH_INFO'][len(XML_RPC_PATH_1):] if path.startswith('/'): path = path[1:] if path.endswith('/'): path = path[:-1] path = path.split('/') # All routes are hard-coded. # No need for a db segment. if len(path) == 1: service = path[0] if service == 'common': if method in ('server_version', ): service = 'db' return xmlrpc_return(start_response, service, method, params) # A db segment must be given. elif len(path) == 2: service, db_name = path params = (db_name, ) + params return xmlrpc_return(start_response, service, method, params) # A db segment and a model segment must be given. elif len(path) == 3 and path[0] == 'model': service, db_name, model_name = path params = (db_name, ) + params[:2] + (model_name, ) + params[2:] service = 'object' return xmlrpc_return(start_response, service, method, params) # The body has been read, need to raise an exception (not return None). fault = xmlrpclib.Fault(RPC_FAULT_CODE_CLIENT_ERROR, '') response = xmlrpclib.dumps(fault, allow_none=None, encoding=None) start_response("200 OK", [('Content-Type', 'text/xml'), ('Content-Length', str(len(response)))]) return [response]
def flush_requests(self, show_timings=False): t1 = time.time() result = None while len(self._pending) > 0: (methodname, params) = self._pending.pop(0) # call a method on the remote server try: request = xmlrpclib.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none) response = self.__transport.request(self.__host, self.__handler, request, verbose=self.__verbose) if len(response) == 1: result = response[0] except KeyboardInterrupt: raise except Exception, e: msg = str(e) if (hasattr(e, "errno")): if (e.errno in [32, 54, 61, 104, 111, 10054, 10061]): self._pending.insert(0, (methodname, params)) t = time.strftime("%H:%M:%S", time.localtime()) self._errors.append("%s -- %s" % (t, msg)) break if ("timed out" in msg): print "XMLRPC timeout, ignoring request" self._timeouts += 1 elif str(e).startswith("<ProtocolError "): self._pending = [] break elif ("exceptions.SystemExit" in str(e)): self._pending = [] break else: msg = "XMLRPC error: %s\nMethod: %s\nParams: %s\n" % \ (str(e), str(methodname), ", ".join([ str(p) for p in params ])) if (not self.raise_errors): print >> sys.stderr, msg else: raise RuntimeError(msg)
def __send(self, methodname, args): self.__ensure_channel() request=xmlrpclib.dumps(args, methodname, encoding=None) # allow_none=False (allow_none is py2.3+) self.__channel.sendall( ("%08d" % (len(request),))+request) resplen=self.__recvall(self.__channel, 8) resplen=int(resplen) response=self.__recvall(self.__channel, resplen) p, u = xmlrpclib.getparser() p.feed(response) p.close() # if the response was a Fault, then it is raised by u.close() try: response=u.close() except xmlrpclib.Fault,e: if e.faultCode!=17: raise e klass,str=e.faultString.split(':', 1) raise common.getfullname(klass)(str)
def _names(self, req, args): """Search on all server keys associated with the requested client key Merge the results while avoiding duplicates. """ cK, pat = args sKs = yield self.info.mapKey(cK) results = {} names = yield self.info.lookup(sKs, pat) for sK, PVs in names.iteritems(): for pv in PVs: results[pv['name']] = pv R = dumps((results.values(), ), methodresponse=True) req.write(R) req.finish()
def encode(self): dict = { "gidCaller": None, "gidObject": None, "lifeTime": self.lifeTime, "privileges": None, "delegate": self.delegate } if self.gidCaller: dict["gidCaller"] = self.gidCaller.save_to_string( save_parents=True) if self.gidObject: dict["gidObject"] = self.gidObject.save_to_string( save_parents=True) if self.privileges: dict["privileges"] = self.privileges.save_to_string() str = xmlrpclib.dumps((dict, ), allow_none=True) self.set_data('URI:http://' + str)
def __init__(self, *args, **kwargs): encoding = kwargs.get('encoding', None) if 'body' not in kwargs and 'params' in kwargs: kw = dict((k, kwargs.pop(k)) for k in DUMPS_ARGS if k in kwargs) kwargs['body'] = xmlrpclib.dumps(**kw) # spec defines that requests must use POST method kwargs.setdefault('method', 'POST') # xmlrpc query multiples times over the same url kwargs.setdefault('dont_filter', True) # restore encoding if encoding is not None: kwargs['encoding'] = encoding super(XmlRpcRequest, self).__init__(*args, **kwargs) self.headers.setdefault('Content-Type', 'text/xml')
def __request(self, methodname, params): # call a method on the remote server request = dumps(params, methodname, encoding=self.__encoding) response = self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose, response = self.blocking ) if self.blocking: if len(response) == 1: response = response[0] return response
def __call__(self, *args): #~ print "%s%r"%(self.methodname, args) scheme, netloc, path, query, frag = urlparse.urlsplit(self.url) xmlreq = xmlrpclib.dumps(args, self.methodname) if scheme == 'scgi': xmlresp = SCGIRequest(self.url).send(xmlreq).replace( "<i8>", "<i4>").replace("</i8>", "</i4>") return xmlrpclib.loads(xmlresp)[0][0] #~ return do_scgi_xmlrpc_request_py(self.url, self.methodname, args) elif scheme == 'http': raise Exception('Unsupported protocol') elif scheme == '': xmlresp = SCGIRequest(self.url).send(xmlreq).replace( "<i8>", "<i4>").replace("</i8>", "</i4>") return xmlrpclib.loads(xmlresp)[0][0] #raise Exception('Unsupported protocol') else: raise Exception('Unsupported protocol')
def findJsonValue(somejson, key): def val(node): # Searches for the next Element Node containing Value e = node.nextSibling while e and e.nodeType != e.ELEMENT_NODE: e = e.nextSibling return (e.getElementsByTagName('string')[0].firstChild.nodeValue if e else None) # parse the JSON as XML #foo_dom = parseString(somejson) foo_dom = parseString(xmlrpclib.dumps(somejson)) # and then search all the name tags which are P1's # and use the val user function to get the value return [ val(node) for node in foo_dom.getElementsByTagName('name') if node.firstChild.nodeValue in key ]
def send(self, response): res = xmlrpclib.dumps(response, methodresponse=True, allow_none=True) length = len(res) self.send_response(200) if length > 1024 and "gzip" in [ s.strip() for s in self.headers.get("accept-encoding", "").split(",") ]: self.send_header("Content-Encoding", "gzip") res = gzip_encode(res) length = len( res ) #TODO: find out if length should be compressed or uncompressed length self.send_header("Content-Length", length) self.send_header("Content-Type", "text/xml") self.end_headers() self.wfile.write(res) self.finish()
def __request(self, methodname, params): request = xmlrpclib.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none) self._probe.getLogger().debug("DEBUG: xml-rpc request: %s" % request) response = self.__transport.request(self.__host, self.__handler, request, verbose=self.__verbose) self._probe.getLogger().debug("DEBUG: xml-rpc response: %s" % response) if len(response) == 1: response = response[0] return response
def _send_response(self, http_code, response): """ write xml headers and response. """ if response: try: response = xmlrpclib.dumps(response, methodresponse=True) except: self.logger.error('Unable to generate XML response', exc_info=True) http_code = 500 response = None self.send_response(http_code) if response: self.send_header('Content-Type', 'text/xml') self.send_header('Content-Length', str(len(response))) self.end_headers() if response: self.wfile.write(response) self.wfile.flush()
def send_rpc(self, cmd, in_fd, out_fd, *args, **kwargs): xml = xmlrpclib.dumps(sum(kwargs.iteritems(), args), cmd) self._debug_fn("calling ikiwiki procedure `%s': [%s]" % (cmd, xml)) _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml) self._debug_fn('reading response from ikiwiki...') xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd) self._debug_fn('read response to procedure %s from ikiwiki: [%s]' % (cmd, xml)) if xml is None: # ikiwiki is going down self._debug_fn('ikiwiki is going down, and so are we...') raise _IkiWikiExtPluginXMLRPCHandler._GoingDown data = xmlrpclib.loads(xml)[0][0] self._debug_fn('parsed data from response to procedure %s: [%s]' % (cmd, data)) return data
class RPCRoot(controllers.Controller): def process_rpc(self,method,params): """ _process_rpc() handles a generic way of dissecting and calling methods and params with params being a list and methods being a '.' delimited string indicating the method to call """ from bkr.server.controllers import Root #Is there a better way to do this? #I could perhaps use cherrypy.root, but this only works on prod obj = Root() # Get the function and make sure it's exposed. for name in method.split('.'): obj = getattr(obj, name, None) # Use the same error message to hide private method names if obj is None or not getattr(obj, "exposed", False): raise AssertionError("method %s does not exist" % name) # Call the method, convert it into a 1-element tuple # as expected by dumps response = obj(*params) return response @turbogears.expose() def RPC2(self, *args, **kw): params, method = xmlrpclib.loads(cherrypy.request.body.read(), use_datetime=True) start = datetime.utcnow() try: if method == "RPC2": # prevent recursion raise AssertionError("method cannot be 'RPC2'") response = self.process_rpc(method,params) response = xmlrpclib.dumps((response,), methodresponse=1, allow_none=True) except identity.IdentityFailure, e: session.rollback() response = xmlrpclib.dumps(xmlrpclib.Fault(1,"%s: %s" % (e.__class__, str(e)))) except xmlrpclib.Fault, fault: session.rollback() log.exception('Error handling XML-RPC method') # Can't marshal the result response = xmlrpclib.dumps(fault)
def call_api(endpoint, params): """Calls the API.""" auth_check() base_url = cfg.get_conf(cfg.ENDPOINT_KEY) username = cfg.get_conf(cfg.USERNAME_KEY) data = xmlrpclib.dumps(params, endpoint) headers = { 'Content-Type': 'text/xml', 'X-User': username, 'X-Pass': cfg.get_password(), 'X-APIVERSION': '2' } req = urllib2.Request(base_url, data, headers) response = urllib2.urlopen(req) raw_xml = response.read() return xmlrpclib.loads(raw_xml)[0][0]
def handle(self, connection): """ connection should be a web.protocol.HttpConnection object (SkunkWeb only, presumably) """ if connection.method != 'POST': raise xmlrpclib.Fault(REQUEST_REFUSED_ERROR, "precondition violated: not an HTTP POST") if self.max_request > 0 and len(connection._stdin) > self.max_request: # see note in handle_cgi about returning a fault connection.setStatus(413) connection.responseHeaders['Content-type'] = 'text/plain' return "request too large" params, method = xmlrpclib.loads(connection._stdin) res = self.dispatch(method, params) connection.setStatus(200) connection.responseHeaders['Content-type'] = 'text/xml' mres = not isinstance(res, xmlrpclib.Fault) return xmlrpclib.dumps(res, methodresponse=mres)
def cryptolog_get_documents(self, name): # tryton trick (extra param on context to retrieve file size) if self.cryptolog_id and self.cryptolog_status == 'completed': if Transaction().context.get('%s.%s' % (self.__name__, name)) == \ 'size': # does not make sense to retrieve the doc juste for the size return 1024 url = config.get(CONFIG_SECTION, 'url') verify = True if config.get(CONFIG_SECTION, 'no_verify') == '1': verify = False method = 'requester.getDocuments' headers = self.cryptolog_headers() auth = self.cryptolog_basic_auth() data = xmlrpclib.dumps((self.cryptolog_id,), method) req = requests.post(url, headers=headers, auth=auth, data=data, verify=verify) response, _ = xmlrpclib.loads(req.content) return response[0][0]['content']
def test_xmlrpc(transfer, encoding): print "\n---> XML Testing transfer=%s, encoding=%s" % (transfer, encoding) data = xmlrpclib.dumps((REFERENCE_XML, ), methodresponse=1) o = transports.Output(transfer=transfer, encoding=encoding) o.set_header('Content-Type', 'text/xml') o.process(data) headers = o.headers # Added by the connection layer headers['Content-Length'] = len(o.data) print "Output: headers: %s" % headers.items() i = transports.Input(headers) io = i.decode(StringIO(o.data)) assert (string.lower(i.type) == 'text/xml') io.seek(0, 0) data = io.read() params, dummy = xmlrpclib.loads(data) assert (REFERENCE_XML == params[0])
def dump(self): """ Dump object to a xmlrpccall. """ for binary_key in self._binary_keys: if isinstance(self[binary_key], list): ## we have list of values self.convert_data[binary_key] = [] for item in self[binary_key]: self.convert_data[binary_key].append( self._encodeData(item)) else: if self[binary_key] is not None: self.convert_data[binary_key] = self._encodeData( self[binary_key]) else: self.convert_data[binary_key] = None for string_key in self._string_keys: self.convert_data[string_key] = self[string_key] return xmlrpclib.dumps((self.convert_data, ), 'GeneratorAnswer', allow_none=1)