Python xmlrpc.client.Fault() Examples

The following are 30 code examples of xmlrpc.client.Fault(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xmlrpc.client , or try the search function .
Example #1
Source File: __init__.py    From PyPlanet with GNU General Public License v3.0 6 votes vote down vote up
def send_loop(self):
		while True:
			await asyncio.sleep(0.25)
			if len(self.send_queue) == 0:
				continue

			# Copy send queue and clear the global one
			queue = self.send_queue.copy()
			self.send_queue.clear()

			# Process and push out the queue.
			try:
				await self.instance.gbx.multicall(*queue)
			except Fault as e:
				if 'Login unknown' in str(e):
					return
				logger.exception(e)
				handle_exception(exception=e, module_name=__name__, func_name='send_loop')
			except Exception as e:
				logger.exception(e)
				handle_exception(exception=e, module_name=__name__, func_name='send_loop') 
Example #2
Source File: xmlrpc.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def _cbRender(self, result, request, responseFailed=None):
        if responseFailed:
            return

        if isinstance(result, Handler):
            result = result.result
        if not isinstance(result, Fault):
            result = (result,)
        try:
            try:
                content = xmlrpclib.dumps(
                    result, methodresponse=True,
                    allow_none=self.allowNone)
            except Exception as e:
                f = Fault(self.FAILURE, "Can't serialize output: %s" % (e,))
                content = xmlrpclib.dumps(f, methodresponse=True,
                                          allow_none=self.allowNone)

            request.setHeader("content-length", str(len(content)))
            request.write(content)
        except:
            log.err()
        request.finish() 
Example #3
Source File: server.py    From Imogen with MIT License 6 votes vote down vote up
def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
        try:
            response = self.dispatchers[path]._marshaled_dispatch(
               data, dispatch_method, path)
        except:
            # report low level exception back to server
            # (each dispatcher should have handled their own
            # exceptions)
            exc_type, exc_value = sys.exc_info()[:2]
            try:
                response = dumps(
                    Fault(1, "%s:%s" % (exc_type, exc_value)),
                    encoding=self.encoding, allow_none=self.allow_none)
                response = response.encode(self.encoding, 'xmlcharrefreplace')
            finally:
                # Break reference cycle
                exc_type = exc_value = None
        return response 
Example #4
Source File: confluence.py    From confluence with MIT License 6 votes vote down vote up
def getAttachments(self, page, space):
        """
        Returns a attachments as a dictionary.

        :param page: The page name
        :type  page: ``str``

        :param space: The space name
        :type  space: ``str``

        :return: dictionary. result['content'] contains the body of the page.
        """
        if self._token2:
            server = self._server.confluence2
            token = self._token2
        else:
            server = self._server.confluence1
            token = self._token1
        existing_page = server.getPage(token, space, page)
        try:
            attachments = server.getAttachments(token, existing_page["id"])
        except xmlrpclib.Fault:
            logging.info("No existing attachment")
            attachments = None
        return attachments 
Example #5
Source File: SpacewalkAPIClient.py    From katprep with GNU General Public License v3.0 6 votes vote down vote up
def __connect(self):
        """
        This function establishes a connection to Spacewalk.
        """
        #set api session and key
        try:
            self.api_session = Server(self.url)
            self.api_key = self.api_session.auth.login(self.username, self.password)
        except Fault as err:
            if err.faultCode == 2950:
                raise InvalidCredentialsException(
                    "Wrong credentials supplied: '%s'", err.faultString
                )
            else:
                raise SessionException(
                    "Generic remote communication error: '%s'", err.faultString
                ) 
Example #6
Source File: confluence.py    From confluence with MIT License 6 votes vote down vote up
def getAttachedFileById(self, id, fileName, version):
        """
        Returns a attachment data as byte[].

        :param id: The page id

        :param fileName: The attached file name
        :type  fileName: ``str``
        """
        if self._token2:
            server = self._server.confluence2
            token = self._token2
        else:
            server = self._server.confluence1
            token = self._token1
        try:
            DATA = server.getAttachmentData(token, id, fileName, version)
        except xmlrpclib.Fault:
            logging.info("No existing attachment")
            DATA = None
        return DATA 
Example #7
Source File: plaso_xmlrpc.py    From plaso with Apache License 2.0 6 votes vote down vote up
def CallFunction(self):
    """Calls the function via RPC."""
    if self._xmlrpc_proxy is None:
      return None

    rpc_call = getattr(self._xmlrpc_proxy, self._RPC_FUNCTION_NAME, None)
    if rpc_call is None:
      return None

    try:
      return rpc_call()  # pylint: disable=not-callable
    except (
        expat.ExpatError, SocketServer.socket.error,
        xmlrpclib.Fault) as exception:
      logger.warning('Unable to make RPC call with error: {0!s}'.format(
          exception))
      return None 
Example #8
Source File: remote.py    From PyPlanet with GNU General Public License v3.0 6 votes vote down vote up
def handle_payload(self, handle_nr, method=None, data=None, fault=None):
		"""
		Handle a callback/response payload or fault.

		:param handle_nr: Handler ID
		:param method: Method name
		:param data: Parsed payload data.
		:param fault: Fault object.
		"""
		if handle_nr in self.handlers:
			await self.handle_response(handle_nr, method, data, fault)
		elif method and data is not None:
			if method == 'ManiaPlanet.ModeScriptCallbackArray':
				await self.handle_scripted(handle_nr, method, data)
			elif method == 'ManiaPlanet.ModeScriptCallback':
				await self.handle_scripted(handle_nr, method, data)
			else:
				await self.handle_callback(handle_nr, method, data)
		elif fault is not None:
			raise TransportException('Handle payload got invalid parameters, see fault exception! {}'.format(fault)) from fault
		else:
			print(method, handle_nr, data)
			logging.warning('Received gbx data, but handle wasn\'t known or payload invalid: handle_nr: {}, method: {}'.format(
				handle_nr, method,
			)) 
Example #9
Source File: serializers.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def update(self, instance, validated_data):
        """Update a Provider instance from validated data."""
        billing_source = validated_data.get("billing_source")
        authentication = validated_data.get("authentication")

        try:
            with ServerProxy(SOURCES_CLIENT_BASE_URL) as sources_client:
                if billing_source:
                    billing_source = self._update_billing_source(instance, billing_source)
                    sources_client.update_billing_source(instance.source_id, billing_source)
                if authentication:
                    authentication = self._update_authentication(instance, authentication)
                    sources_client.update_authentication(instance.source_id, authentication)
        except Fault as error:
            LOG.error(f"Sources update error: {error}")
            raise SourcesStorageError(str(error))
        except (ConnectionRefusedError, gaierror, ProtocolError) as error:
            LOG.error(f"Sources update dependency error: {error}")
            raise SourcesDependencyError(f"Sources-client: {error}")
        return get_source_instance(instance.source_id) 
Example #10
Source File: dokuwiki.py    From python-dokuwiki with MIT License 6 votes vote down vote up
def send(self, command, *args, **kwargs):
        """Generic method for executing an XML-RPC *command*. *args* and
        *kwargs* are the arguments and parameters needed by the command.
        """
        args = list(args)
        if kwargs:
            args.append(kwargs)

        method = self.proxy
        for elt in command.split('.'):
            method = getattr(method, elt)

        try:
            return method(*args)
        except Fault as err:
            if err.faultCode == 121:
                return {}
            elif err.faultCode == 321:
                return []
            raise DokuWikiError(err)
        except ExpatError as err:
            if str(err) != ERR:
                raise DokuWikiError(err) 
Example #11
Source File: connection.py    From python-mysql-pool with MIT License 6 votes vote down vote up
def is_connected(self):
        """Check whether connection with Fabric is valid

        Return True if we can still interact with the Fabric server; False
        if Not.

        Returns True or False.
        """
        try:
            self._proxy._some_nonexisting_method()  # pylint: disable=W0212
        except Fault:
            return True
        except (TypeError, AttributeError):
            return False
        else:
            return False 
Example #12
Source File: connection.py    From python-mysql-pool with MIT License 6 votes vote down vote up
def execute(self, group, command, *args, **kwargs):
        """Executes the given command with MySQL protocol

        Executes the given command with the given parameters.

        Returns an iterator to navigate to navigate through the result set
        returned by Fabric
        """
        params = self.create_params(*args, **kwargs)
        cmd = "CALL {0}.{1}({2})".format(group, command, params)

        fab_set = None
        try:
            data = self._execute_cmd(cmd)
            fab_set = FabricMySQLSet(data)
        except (Fault, socket.error, InterfaceError) as exc:
            msg = "Executing {group}.{command} failed: {error}".format(
                group=group, command=command, error=str(exc))
            raise InterfaceError(msg)

        return fab_set 
Example #13
Source File: connection.py    From python-mysql-pool with MIT License 6 votes vote down vote up
def report_failure(self, server_uuid, errno):
        """Report failure to Fabric

        This method sets the status of a MySQL server identified by
        server_uuid.
        """
        if not self._report_errors:
            return

        errno = int(errno)
        current_host = socket.getfqdn()

        if errno in REPORT_ERRORS or errno in REPORT_ERRORS_EXTRA:
            _LOGGER.debug("Reporting error %d of server %s", errno,
                          server_uuid)
            inst = self.get_instance()
            try:
                data = inst.execute('threat', 'report_failure',
                                    server_uuid, current_host, errno)
                FabricResponse(data)
            except (Fault, socket.error) as exc:
                _LOGGER.debug("Failed reporting server to Fabric (%s)",
                              str(exc))
                # Not requiring further action 
Example #14
Source File: connection.py    From python-mysql-pool with MIT License 6 votes vote down vote up
def execute(self, group, command, *args, **kwargs):
        """Executes the given command with XML-RPC protocol

        Executes the given command with the given parameters

        Returns an iterator to navigate to navigate through the result set
        returned by Fabric
        """
        try:
            grp = getattr(self.handler.proxy, group)
            cmd = getattr(grp, command)
        except AttributeError as exc:
            raise ValueError("{group}.{command} not available ({err})".format(
                group=group, command=command, err=str(exc)))

        fab_set = None
        try:
            data = cmd(*args, **kwargs)
            fab_set = FabricSet(data)
        except (Fault, socket.error, InterfaceError) as exc:
            msg = "Executing {group}.{command} failed: {error}".format(
                group=group, command=command, error=str(exc))
            raise InterfaceError(msg)

        return fab_set 
Example #15
Source File: query.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def execute(self):  # pragma: no cover
		"""
		Execute the chat message sending query. Please don't use this when you send multiple chat messages or actions!

		:return: Result of query.
		"""
		try:
			return await self.gbx_query.execute()
		except Fault as e:
			if 'Login unknown' in e.faultString:
				return True  # Ignore
			raise 
Example #16
Source File: call.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def execute(self, player, action, values, *_, **__):
		self.method['last_input'] = values['call_value_field']
		input_values = str(values['call_value_field']).splitlines()
		args = list()

		if len(self.method['inputs']) > 0:
			for idx, input in enumerate(self.method['inputs']):
				if len(input_values) <= idx:
					await self.parent.app.instance.chat('$ff0Warning: Not enough inputs given for the call!')
					continue

				args.append(self.convert_type(input_values[idx], input))

		# Execute call.
		try:
			logging.getLogger(__name__).warning('Executing GBX in-game: {}, {}'.format(self.method['method'], args))
			result = await self.parent.app.instance.gbx(self.method['method'], *args)
			self.method['result'] = self.format_output(result)

			# Refresh with results.
			await self.display()
		except Fault as e:
			logging.getLogger(__name__).warning('Executing GBX in-game, fault thrown: {}'.format(str(e)))
			self.method['error'] = '{}: {}'.format(e.faultCode, e.faultString)

			# Refresh with error.
			await self.display()
		except Exception as e:
			logging.getLogger(__name__).warning('Executing GBX in-game, error thrown: {}'.format(str(e)))
			await self.hide([player.login])
			self.response_future.set_result(False)
			self.response_future.done() 
Example #17
Source File: gandi.py    From lexicon with MIT License 5 votes vote down vote up
def authenticate(self):
        """Determine the current domain and zone IDs for the domain."""
        try:
            payload = self._api.domain.info(self._api_key, self._domain)
            self._zone_id = payload['zone_id']
            return payload['id']
        except xmlrpclib.Fault as err:
            raise Exception("Failed to authenticate: '{0}'".format(err))

    # Create record. If record already exists with the same content, do nothing. 
Example #18
Source File: magento_api.py    From python-magento with MIT License 5 votes vote down vote up
def keep_session_alive(self):
        """If the session expired, logs back in."""

        try:
            self.resources()
        except xmlrpclib.Fault as fault:
            if fault.faultCode == 5:
                self.login()
            else:
                raise 
Example #19
Source File: xmlrpc.py    From peach with Mozilla Public License 2.0 5 votes vote down vote up
def lookupProcedure(self, procedurePath):
        """
        Given a string naming a procedure, return a callable object for that
        procedure or raise NoSuchFunction.

        The returned object will be called, and should return the result of the
        procedure, a Deferred, or a Fault instance.

        Override in subclasses if you want your own policy.  The base
        implementation that given C{'foo'}, C{self.xmlrpc_foo} will be returned.
        If C{procedurePath} contains C{self.separator}, the sub-handler for the
        initial prefix is used to search for the remaining path.

        If you override C{lookupProcedure}, you may also want to override
        C{listProcedures} to accurately report the procedures supported by your
        resource, so that clients using the I{system.listMethods} procedure
        receive accurate results.

        @since: 11.1
        """
        if procedurePath.find(self.separator) != -1:
            prefix, procedurePath = procedurePath.split(self.separator, 1)
            handler = self.getSubHandler(prefix)
            if handler is None:
                raise NoSuchFunction(self.NOT_FOUND,
                    "no such subHandler %s" % prefix)
            return handler.lookupProcedure(procedurePath)

        f = getattr(self, "xmlrpc_%s" % procedurePath, None)
        if not f:
            raise NoSuchFunction(self.NOT_FOUND,
                "procedure %s not found" % procedurePath)
        elif not callable(f):
            raise NoSuchFunction(self.NOT_FOUND,
                "procedure %s not callable" % procedurePath)
        else:
            return f 
Example #20
Source File: xmlrpc.py    From peach with Mozilla Public License 2.0 5 votes vote down vote up
def _ebRender(self, failure):
        if isinstance(failure.value, Fault):
            return failure.value
        log.err(failure)
        return Fault(self.FAILURE, "error") 
Example #21
Source File: manager.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def add_map(self, filename, insert=True, save_matchsettings=True):
		"""
		Add or insert map to current online playlist.

		:param filename: Load from filename relative to the 'Maps' directory on the dedicated host server.
		:param insert: Insert after the current map, this will make it play directly after the current map. True by default.
		:param save_matchsettings: Save match settings as well.
		:type filename: str
		:type insert: bool
		:type save_matchsettings: bool
		:raise: pyplanet.contrib.map.exceptions.MapIncompatible
		:raise: pyplanet.contrib.map.exceptions.MapException
		"""
		gbx_method = 'InsertMap' if insert else 'AddMap'

		try:
			result = await self._instance.gbx(gbx_method, filename)
		except Fault as e:
			if 'unknown' in e.faultString:
				raise MapNotFound('Map is not found on the server.')
			elif 'already' in e.faultString:
				raise MapException('Map already added to server.')
			raise MapException(e.faultString)

		# Try to save match settings.
		try:
			if save_matchsettings:
				await self.save_matchsettings()
		except Exception as e:
			handle_exception(e, __name__, 'add_map', extra_data={'EXTRAHOOK': 'Map Insert bug, see #306'})

		return result 
Example #22
Source File: server.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def system_multicall(self, call_list):
        """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
[[4], ...]

        Allows the caller to package multiple XML-RPC calls into a single
        request.

        See http://www.xmlrpc.com/discuss/msgReader$1208
        """

        results = []
        for call in call_list:
            method_name = call['methodName']
            params = call['params']

            try:
                # XXX A marshalling error in any response will fail the entire
                # multicall. If someone cares they should fix this.
                results.append([self._dispatch(method_name, params)])
            except Fault as fault:
                results.append(
                    {'faultCode' : fault.faultCode,
                     'faultString' : fault.faultString}
                    )
            except:
                exc_type, exc_value, exc_tb = sys.exc_info()
                results.append(
                    {'faultCode' : 1,
                     'faultString' : "%s:%s" % (exc_type, exc_value)}
                    )
        return results 
Example #23
Source File: xmlrpc.py    From peach with Mozilla Public License 2.0 5 votes vote down vote up
def render_POST(self, request):
        request.content.seek(0, 0)
        request.setHeader("content-type", "text/xml")
        try:
            if self.useDateTime:
                args, functionPath = xmlrpclib.loads(request.content.read(),
                    use_datetime=True)
            else:
                # Maintain backwards compatibility with Python < 2.5
                args, functionPath = xmlrpclib.loads(request.content.read())
        except Exception as e:
            f = Fault(self.FAILURE, "Can't deserialize input: %s" % (e,))
            self._cbRender(f, request)
        else:
            try:
                function = self.lookupProcedure(functionPath)
            except Fault as f:
                self._cbRender(f, request)
            else:
                # Use this list to track whether the response has failed or not.
                # This will be used later on to decide if the result of the
                # Deferred should be written out and Request.finish called.
                responseFailed = []
                request.notifyFinish().addErrback(responseFailed.append)
                if getattr(function, 'withRequest', False):
                    d = defer.maybeDeferred(function, request, *args)
                else:
                    d = defer.maybeDeferred(function, *args)
                d.addErrback(self._ebRender)
                d.addCallback(self._cbRender, request, responseFailed)
        return server.NOT_DONE_YET 
Example #24
Source File: test_xmlrpc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_cgi_xmlrpc_response(self):
        data = """<?xml version='1.0'?>
        <methodCall>
            <methodName>test_method</methodName>
            <params>
                <param>
                    <value><string>foo</string></value>
                </param>
                <param>
                    <value><string>bar</string></value>
                </param>
            </params>
        </methodCall>
        """

        with support.EnvironmentVarGuard() as env, \
             captured_stdout(encoding=self.cgi.encoding) as data_out, \
             support.captured_stdin() as data_in:
            data_in.write(data)
            data_in.seek(0)
            env['CONTENT_LENGTH'] = str(len(data))
            self.cgi.handle_request()
        data_out.seek(0)

        # will respond exception, if so, our goal is achieved ;)
        handle = data_out.read()

        # start with 44th char so as not to get http header, we just
        # need only xml
        self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])

        # Also test the content-length returned  by handle_request
        # Using the same test method inorder to avoid all the datapassing
        # boilerplate code.
        # Test for bug: http://bugs.python.org/issue5040

        content = handle[handle.find("<?xml"):]

        self.assertEqual(
            int(re.search('Content-Length: (\d+)', handle).group(1)),
            len(content)) 
Example #25
Source File: test_xmlrpc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_path3(self):
        p = xmlrpclib.ServerProxy(URL+"/is/broken")
        self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)

#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
#does indeed serve subsequent requests on the same connection 
Example #26
Source File: test_xmlrpc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_path2(self):
        p = xmlrpclib.ServerProxy(URL+"/foo/bar")
        self.assertEqual(p.add(6,8), 6+8)
        self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8) 
Example #27
Source File: test_xmlrpc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_dump_fault(self):
        f = xmlrpclib.Fault(42, 'Test Fault')
        s = xmlrpclib.dumps((f,))
        (newf,), m = xmlrpclib.loads(s)
        self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
        self.assertEqual(m, None)

        s = xmlrpclib.Marshaller().dumps(f)
        self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s) 
Example #28
Source File: test_xmlrpc.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_repr(self):
        f = xmlrpclib.Fault(42, 'Test Fault')
        self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
        self.assertEqual(repr(f), str(f)) 
Example #29
Source File: server.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
        try:
            response = self.dispatchers[path]._marshaled_dispatch(
               data, dispatch_method, path)
        except:
            # report low level exception back to server
            # (each dispatcher should have handled their own
            # exceptions)
            exc_type, exc_value = sys.exc_info()[:2]
            response = dumps(
                Fault(1, "%s:%s" % (exc_type, exc_value)),
                encoding=self.encoding, allow_none=self.allow_none)
            response = response.encode(self.encoding)
        return response 
Example #30
Source File: test_testcase.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def test_update_author_should_fail_for_non_existing_email(self):
        initial_author_email = self.testcase.author.email
        with self.assertRaises(Fault):
            self.rpc_client.TestCase.update(  # pylint: disable=objects-update-used
                self.testcase.pk,
                {
                    'author': self.non_existing_email,
                }
            )

        self.testcase.refresh_from_db()
        self.assertEqual(initial_author_email, self.testcase.author.email)