twisted.internet.defer.fail

Here are the examples of the python api twisted.internet.defer.fail taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: pika
Source File: twisted_connection.py
View license
    def basic_publish(self, *args, **kwargs):
        """Make sure the channel is not closed and then publish. Return a
        Deferred that fires with the result of the channel's basic_publish.

        """
        if self.__closed:
            return defer.fail(self.__closed)
        return defer.succeed(self.__channel.basic_publish(*args, **kwargs))

Example 2

View license
    def test_returns_404_if_key_not_found(self):
        request = DummyRequest(['/keys'])
        request.addArg('search', '[email protected]')
        when(self.keymanager).get_key('[email protected]').thenReturn(defer.fail(KeyNotFound()))

        d = self.web.get(request)

        def assert_404(_):
            self.assertEquals(404, request.code)

        d.addCallback(assert_404)
        return d

Example 3

View license
    def test_fingerprint_missing(self):
        key = OpenPGPKey(MAIL_ADDRESS)
        key.fingerprint = FINGERPRINT
        request = DummyRequest(['/user-settings'])
        when(self.keymanager).get_key(MAIL_ADDRESS).thenReturn(defer.fail(Failure))

        d = self.web.get(request)

        def assert_response(_):
            response = json.loads(request.written[0])
            self.assertEqual(FINGERPRINT_NOT_FOUND, response['fingerprint'])
            self.assertEqual(MAIL_ADDRESS, response['account_email'])

        d.addCallback(assert_response)
        return d

Example 4

Project: hellanzb
Source File: helladb.py
View license
    def headRequest(self, group, index, id = None):
        if id is not None:
            try:
                xref = self.dbm['Message-IDs'][id]
            except KeyError:
                return defer.fail(NewsServerError("No such article: " + id))
            else:
                group, index = xref[0]
                index = int(index)
        
        try:
            a = self.dbm['groups'][group].articles[index]
        except KeyError:
            return defer.fail(NewsServerError("No such group: " + group))
        else:
            return defer.succeed((index, a.getHeader('Message-ID'), a.textHeaders()))

Example 5

Project: hellanzb
Source File: helladb.py
View license
    def bodyRequest(self, group, index, id = None):
        if id is not None:
            try:
                #xref = self.dbm['Message-IDs'][id]
                print 'DOH!' + id
                body = self.dbm[id]
            except KeyError:
                return defer.fail(NewsServerError("No such article: " + id))
            else:
                print 'HI!' + id
                return defer.succeed((0, id, StringIO.StringIO(body)))
                #group, index = xref[0]
                #index = int(index)

                """

Example 6

Project: airpnp
Source File: test_device_builder.py
View license
    def test_build_device_error_with_missing_service(self, pageMock):
        def fetch(*args, **kw):
            def fetch2(*args, **kw):
                # second time: 404 Not Found
                return defer.fail(error.Error(http.NOT_FOUND, 'Not Found', 'Not Found'))
            pageMock.side_effect = fetch2
            # first time: return document
            return defer.succeed(readall('ms.xml'))
        pageMock.side_effect = fetch
        builder = DeviceBuilder(Mock(), lambda x: (True, None))
        actual = builder.build('')
        err = [None]
        actual.addErrback(lambda x: err.__setitem__(0, x))

        self.assertEqual(err[0].type, error.Error)

Example 7

Project: airpnp
Source File: test_device_builder.py
View license
    def test_failure_from_builder_contains_url(self, pageMock):
        pageMock.return_value = defer.fail(error.Error(http.NOT_FOUND, 'Not Found', 'Not Found'))
        builder = DeviceBuilder(Mock(), lambda x: (True, None))
        actual = builder.build('http://www.dummy.com')

        err = [None]
        actual.addErrback(lambda x: err.__setitem__(0, x))

        self.assertEqual(err[0].url, 'http://www.dummy.com')

Example 8

Project: airpnp
Source File: test_device_builder.py
View license
    def test_failure_from_builder_contains_url_when_service_fetching_fails(self, pageMock):
        def fetch(*args, **kw):
            def fetch2(*args, **kw):
                # second time: 404 Not Found
                return defer.fail(error.Error(http.NOT_FOUND, 'Not Found', 'Not Found'))
            pageMock.side_effect = fetch2
            # first time: return document
            return defer.succeed(readall('ms.xml'))
        pageMock.side_effect = fetch
        builder = DeviceBuilder(Mock(), lambda x: (True, None))
        actual = builder.build('http://www.dummy.com')

        err = [None]
        actual.addErrback(lambda x: err.__setitem__(0, x))

        self.assertEqual(err[0].url, 'http://www.dummy.com/cds.xml')

Example 9

Project: airpnp
Source File: test_util.py
View license
    def test_soap_error_on_500_response(self, pageMock):
        # Setup mock
        f = failure.Failure(error.Error(http.INTERNAL_SERVER_ERROR, 'Internal Error', 
                                        SoapError(501, 'Action Failed').tostring()))
        pageMock.return_value = defer.fail(f)

        # Given
        msg = SoapMessage('urn:schemas-upnp-org:service:ConnectionManager:1', 'GetCurrentConnectionIDs')

        # When
        d = send_soap_message_deferred('http://www.dummy.com', msg)

        # Then
        response = d.result
        self.assertEqual(response.__class__, SoapError)
        self.assertEqual(response.code, '501')

Example 10

Project: airpnp
Source File: test_util.py
View license
    def test_unrecognized_error_is_reraised(self, pageMock):
        # Setup mock
        f = failure.Failure(error.Error(http.NOT_FOUND, 'Not Found', 'Not Found'))
        pageMock.return_value = defer.fail(f)

        # Given
        msg = SoapMessage('urn:schemas-upnp-org:service:ConnectionManager:1', 'GetCurrentConnectionIDs')

        # When
        d = send_soap_message_deferred('http://www.dummy.com', msg)

        # Then
        f = d.result
        self.assertTrue(f.check(error.Error))

Example 11

Project: cache-busters
Source File: test_caches.py
View license
    def test_delete_errbacks_when_any_errback(self):
        cache = MultiCache([
            pretend.stub(delete=lambda key: fail(ValueError()))
        ])
        d = cache.delete("foo")
        exc = self.failureResultOf(d)
        self.assertIsInstance(exc.value.subFailure.value, ValueError)

Example 12

Project: cache-busters
Source File: test_driver.py
View license
    def test_invalidate_row_succeeds_on_cache_delete_failure(self):
        cache = pretend.stub(
            delete=lambda key: fail(Exception()),
        )
        d = Driver(FormattingKeyMaker({
            "foo_table": ["bar"]
        }), cache, DummyLogger())
        invalidate_d = d.invalidate_row("foo_table", {})
        res = self.successResultOf(invalidate_d)
        self.assertIs(res, None)

Example 13

Project: cache-busters
Source File: test_driver.py
View license
    def test_invalidate_row_logs_on_cache_delete_failure(self):
        f = Failure(Exception())
        cache = pretend.stub(
            delete=lambda key: fail(f),
        )
        logger = pretend.stub(
            msg=lambda s, **kwargs: None,
            err=pretend.call_recorder(lambda failure, table, key: None)
        )
        d = Driver(FormattingKeyMaker({
            "foo_table": ["bar"]
        }), cache, logger)
        d.invalidate_row("foo_table", {})
        self.assertEqual(logger.err.calls, [
            pretend.call(f, table="foo_table", key="bar")
        ])

Example 14

Project: cache-busters
Source File: test_driver.py
View license
    def test_invalidate_row_logs_failure_counts(self):
        cache = pretend.stub(
            delete=lambda key: fail(Exception())
        )
        logger = pretend.stub(
            err=lambda failure, table, key: None,
            msg=pretend.call_recorder(lambda *args, **kwargs: None)
        )
        d = Driver(FormattingKeyMaker({
            "foo_table": ["bar"]
        }), cache, logger)
        d.invalidate_row("foo_table", {})
        self.assertEqual(logger.msg.calls, [
            pretend.call("cache_buster.driver.invalidated_rows",
                deletes=0, nonexistant=0, failures=1,
            )
        ])

Example 15

Project: silverberg
Source File: test_cluster.py
View license
    def test_two_nodes_down(self):
        """
        If 2 cass nodes are down, it tries the next node in cluster
        """
        cluster = RoundRobinCassandraCluster(['one', 'two', 'three'], 'keyspace')
        self.clients[1].execute.return_value = defer.fail(ConnectionRefusedError())
        self.clients[2].execute.return_value = defer.fail(NoRouteError())
        result = cluster.execute(2, 3)
        self.clients[1].execute.assert_called_once_with(2, 3)
        self.clients[2].execute.assert_called_once_with(2, 3)
        self.clients[0].execute.assert_called_once_with(2, 3)
        self.assertEqual(self.successResultOf(result), 'exec_ret1')

Example 16

Project: silverberg
Source File: test_cluster.py
View license
    def test_other_error_propogated(self):
        """
        Any error other than subclass of ``ConnectError`` is propgoated
        """
        cluster = RoundRobinCassandraCluster(['one', 'two', 'three'], 'keyspace')
        rand_err = ValueError('random err')
        self.clients[1].execute.return_value = defer.fail(rand_err)
        result = cluster.execute(2, 3)
        self.assertEqual(self.failureResultOf(result).value, rand_err)
        self.assertEqual(self.clients[2].execute.called, False)
        self.assertEqual(self.clients[0].execute.called, False)

Example 17

Project: silverberg
Source File: test_cluster.py
View license
    def test_other_error_propogated_on_node_down(self):
        """
        If first node gives ``ConnectError`` then second node is tried if it gives
        error other than subclass of ``ConnectError`` it is propogated
        """
        cluster = RoundRobinCassandraCluster(['one', 'two', 'three'], 'keyspace')
        self.clients[1].execute.return_value = defer.fail(NoRouteError())
        rand_err = ValueError('random err')
        self.clients[2].execute.return_value = defer.fail(rand_err)
        result = cluster.execute(2, 3)
        self.assertEqual(self.failureResultOf(result).value, rand_err)
        self.assertEqual(self.clients[0].execute.called, False)

Example 18

Project: silverberg
Source File: test_cluster.py
View license
    def test_all_nodes_down(self):
        """
        If all cass nodes are down, it gives up eventually by raising the
        connection error exception
        """
        cluster = RoundRobinCassandraCluster(['one', 'two', 'three'], 'keyspace')
        err = ConnectionRefusedError()
        for i in range(3):
            self.clients[i].execute.side_effect = lambda *_: defer.fail(err)

        result = cluster.execute(2, 3)

        self.assertEqual(self.failureResultOf(result).value, err)
        for i in range(3):
            self.clients[i].execute.assert_called_once_with(2, 3)

Example 19

Project: silverberg
Source File: test_cluster.py
View license
    def test_multiple_clients(self):
        """
        When multiple clients execute simultaneously, it does not skip nodes. It basically ensures
        that http://bit.ly/1csEIRR situation does not happen
        """
        cluster = RoundRobinCassandraCluster(['one', 'two', 'three'], 'keyspace')

        def _execute(*args):
            cluster.execute(2, 3)
            return defer.fail(NoRouteError())
        self.clients[1].execute.side_effect = _execute

        result = cluster.execute(2, 3)

        self.assertEqual(self.successResultOf(result), 'exec_ret3')
        self.assertEqual(self.clients[2].execute.call_args_list, [mock.call(2, 3)] * 2)
        self.clients[1].execute.assert_called_once_with(2, 3)

Example 20

Project: silverberg
Source File: test_lock.py
View license
    def test_ensure_schema_already_created(self):
        """
        BasicLock.ensure_schema doesn't explode on InvalidRequestException,
        meaning the table already exists.
        """
        def _side_effect(*args, **kwargs):
            return defer.fail(InvalidRequestException())
        self.client.execute.side_effect = _side_effect

        d = BasicLock.ensure_schema(self.client, 'lock')
        self.successResultOf(d)

Example 21

Project: idavoll
Source File: backend.py
View license
    def subscribe(self, nodeIdentifier, subscriber, requestor):
        subscriberEntity = subscriber.userhostJID()
        if subscriberEntity != requestor.userhostJID():
            return defer.fail(error.Forbidden())

        d = self.storage.getNode(nodeIdentifier)
        d.addCallback(_getAffiliation, subscriberEntity)
        d.addCallback(self._doSubscribe, subscriber)
        return d

Example 22

Project: idavoll
Source File: backend.py
View license
    def unsubscribe(self, nodeIdentifier, subscriber, requestor):
        if subscriber.userhostJID() != requestor.userhostJID():
            return defer.fail(error.Forbidden())

        d = self.storage.getNode(nodeIdentifier)
        d.addCallback(lambda node: node.removeSubscription(subscriber))
        return d

Example 23

Project: idavoll
Source File: backend.py
View license
    def getNodeConfiguration(self, nodeIdentifier):
        if not nodeIdentifier:
            return defer.fail(error.NoRootNode())

        d = self.storage.getNode(nodeIdentifier)
        d.addCallback(lambda node: node.getConfiguration())

        return d

Example 24

Project: idavoll
Source File: backend.py
View license
    def setNodeConfiguration(self, nodeIdentifier, options, requestor):
        if not nodeIdentifier:
            return defer.fail(error.NoRootNode())

        d = self.storage.getNode(nodeIdentifier)
        d.addCallback(_getAffiliation, requestor)
        d.addCallback(self._doSetNodeConfiguration, options)
        return d

Example 25

Project: idavoll
Source File: memory_storage.py
View license
    def getCallbacks(self, service, nodeIdentifier):
        try:
            callbacks = self.callbacks[service, nodeIdentifier]
        except KeyError:
            return defer.fail(error.NoCallbacks())
        else:
            return defer.succeed(callbacks)

Example 26

Project: wokkel
Source File: xmppim.py
View license
    def _onRosterSet(self, iq):
        def trapIgnored(failure):
            failure.trap(RosterPushIgnored)
            raise error.StanzaError('service-unavailable')

        request = RosterRequest.fromElement(iq)

        if (not self.allowAnySender and
                request.sender and
                request.sender.userhostJID() !=
                self.parent.jid.userhostJID()):
            d = defer.fail(RosterPushIgnored())
        elif request.item.remove:
            d = defer.maybeDeferred(self.removeReceived, request)
        else:
            d = defer.maybeDeferred(self.setReceived, request)
        d.addErrback(trapIgnored)
        return d

Example 27

View license
    def test_render_deferred_fail(self, render_mock, log_err_mock):
        exc = Exception('boom')
        render_mock.return_value = fail(exc)
        result = self.resource.render(self.request)
        self.assertEqual(result, server.NOT_DONE_YET)
        self.assertTrue(self.request.write.called)
        self.assertTrue(self.request.finish.called)
        self.assertEqual(len(self.request_write_values), 1)
        obj = json.loads(self.request_write_values[0])
        self.assertEqual(obj['status'], 'error')
        self.assertEqual(obj['message'], exc.message)
        self.assertEqual(obj['code'], 500)
        self.assertTrue(log_err_mock.called)

Example 28

Project: scrapy
Source File: endpoints.py
View license
    def connect(self, protocolFactory):
        """
        Implement L{IStreamClientEndpoint.connect} to connect via TCP.
        """
        try:
            wf = _WrappingFactory(protocolFactory)
            self._reactor.connectTCP(
                self._host, self._port, wf,
                timeout=self._timeout, bindAddress=self._bindAddress)
            return wf._onConnection
        except:
            return defer.fail()

Example 29

Project: scrapy
Source File: endpoints.py
View license
    def connect(self, protocolFactory):
        """
        Implement L{IStreamClientEndpoint.connect} to connect with SSL over
        TCP.
        """
        try:
            wf = _WrappingFactory(protocolFactory)
            self._reactor.connectSSL(
                self._host, self._port, wf, self._sslContextFactory,
                timeout=self._timeout, bindAddress=self._bindAddress)
            return wf._onConnection
        except:
            return defer.fail()

Example 30

Project: scrapy
Source File: endpoints.py
View license
    def connect(self, protocolFactory):
        """
        Implement L{IStreamClientEndpoint.connect} to connect via a
        UNIX Socket
        """
        try:
            wf = _WrappingFactory(protocolFactory)
            self._reactor.connectUNIX(
                self._path, wf,
                timeout=self._timeout,
                checkPID=self._checkPID)
            return wf._onConnection
        except:
            return defer.fail()

Example 31

Project: scrapy
Source File: endpoints.py
View license
    def listen(self, factory):
        """
        Implement L{IStreamServerEndpoint.listen} to start listening on, and
        then close, C{self._fileno}.
        """
        if self._used:
            return defer.fail(error.AlreadyListened())
        self._used = True

        try:
            self._setNonBlocking(self.fileno)
            port = self.reactor.adoptStreamPort(
                self.fileno, self.addressFamily, factory)
            self._close(self.fileno)
        except:
            return defer.fail()
        return defer.succeed(port)

Example 32

Project: SimpleDNS
Source File: dnsproxy.py
View license
    def queryTCP(self, queries, timeout=10):
        if not len(self.connections):
            address = self.pickServer(queries)
            if address is None:
                return defer.fail(IOError("No domain name servers available"))
            host, port = address
            self._reactor.connectTCP(host, port, self.factory)
            self.pending.append((defer.Deferred(), queries, timeout))
            return self.pending[-1][0]
        else:
            return self.connections[0].query(queries, timeout)

Example 33

Project: smap
Source File: republisher.py
View license
    def update_topics(self, q):
        parser = qp.QueryParser(self.request)
        query = "select distinct uuid where (%s)" % q
        try:
            d = parser.runquery(self.db, query)
        except SmapException, e:
            return defer.fail(e)
        else:
            d.addCallback(self.set_topics)
        return d

Example 34

Project: openross
Source File: engine.py
View license
    def health_check_image(self, payload, **kwargs):
        """ Health check needs a different succeed/fail check than the normal pipeline
        """

        def _healthcheck_finished(output, payload, **kwargs):
            """ Callback to ensure size is what is expected """
            if isinstance(output, Failure):
                return defer.fail(output)
            else:
                required_size = settings.HEALTH_EXPECTED_SIZE[payload['mode']]
                if payload['resized_width'] == required_size[0] \
                        and payload['resized_height'] == required_size[1]:
                    return defer.succeed(output)
                else:
                    return defer.fail()

        d = self.imageproc.process_image(payload, **kwargs)
        d.addBoth(_healthcheck_finished, payload, **kwargs)
        return d

Example 35

Project: openross
Source File: engine.py
View license
    def _imageproc_finished(self, output, payload, **kwargs):
        """Processing of images leaving the pipeline """
        if isinstance(output, Failure):
            if settings.DEBUG:
                log.err(
                    'Error Processing %s' % payload['image_path'], logLevel=logging.ERROR)
            return defer.fail(output)
        else:
            if settings.DEBUG:
                log.msg('IMG: %s - done' % payload['image_path'])
            return defer.succeed(output)

Example 36

Project: tahoe-lafs
Source File: test_i2p_provider.py
View license
    def test_try_handled_error(self):
        reactor = object()
        txi2p = mock.Mock()
        d = defer.fail(error.ConnectError("oops"))
        txi2p.testAPI = mock.Mock(return_value=d)
        ep = object()
        stdout = StringIO()
        with mock.patch("allmydata.util.i2p_provider.clientFromString",
                        return_value=ep) as cfs:
            d = i2p_provider._try_to_connect(reactor, "desc", stdout, txi2p)
        r = self.successResultOf(d)
        self.assertIs(r, None)
        cfs.assert_called_with(reactor, "desc")
        txi2p.testAPI.assert_called_with(reactor, 'SAM', ep)
        self.assertEqual(stdout.getvalue(),
                         "Unable to reach I2P SAM API at 'desc': "
                         "An error occurred while connecting: oops.\n")

Example 37

Project: tahoe-lafs
Source File: test_i2p_provider.py
View license
    def test_try_unhandled_error(self):
        reactor = object()
        txi2p = mock.Mock()
        d = defer.fail(ValueError("oops"))
        txi2p.testAPI = mock.Mock(return_value=d)
        ep = object()
        stdout = StringIO()
        with mock.patch("allmydata.util.i2p_provider.clientFromString",
                        return_value=ep) as cfs:
            d = i2p_provider._try_to_connect(reactor, "desc", stdout, txi2p)
        f = self.failureResultOf(d)
        self.assertIsInstance(f.value, ValueError)
        self.assertEqual(str(f.value), "oops")
        cfs.assert_called_with(reactor, "desc")
        txi2p.testAPI.assert_called_with(reactor, 'SAM', ep)
        self.assertEqual(stdout.getvalue(), "")

Example 38

Project: tahoe-lafs
Source File: test_tor_provider.py
View license
    def test_try_handled_error(self):
        reactor = object()
        txtorcon = mock.Mock()
        d = defer.fail(error.ConnectError("oops"))
        txtorcon.build_tor_connection = mock.Mock(return_value=d)
        ep = object()
        stdout = StringIO()
        with mock.patch("allmydata.util.tor_provider.clientFromString",
                        return_value=ep) as cfs:
            d = tor_provider._try_to_connect(reactor, "desc", stdout, txtorcon)
        r = self.successResultOf(d)
        self.assertIs(r, None)
        cfs.assert_called_with(reactor, "desc")
        txtorcon.build_tor_connection.assert_called_with(ep)
        self.assertEqual(stdout.getvalue(),
                         "Unable to reach Tor at 'desc': "
                         "An error occurred while connecting: oops.\n")

Example 39

Project: tahoe-lafs
Source File: test_tor_provider.py
View license
    def test_try_unhandled_error(self):
        reactor = object()
        txtorcon = mock.Mock()
        d = defer.fail(ValueError("oops"))
        txtorcon.build_tor_connection = mock.Mock(return_value=d)
        ep = object()
        stdout = StringIO()
        with mock.patch("allmydata.util.tor_provider.clientFromString",
                        return_value=ep) as cfs:
            d = tor_provider._try_to_connect(reactor, "desc", stdout, txtorcon)
        f = self.failureResultOf(d)
        self.assertIsInstance(f.value, ValueError)
        self.assertEqual(str(f.value), "oops")
        cfs.assert_called_with(reactor, "desc")
        txtorcon.build_tor_connection.assert_called_with(ep)
        self.assertEqual(stdout.getvalue(), "")

Example 40

Project: tahoe-lafs
Source File: pipeline.py
View license
    def add(self, _size, _func, *args, **kwargs):
        # We promise that all the Deferreds we return will fire in the order
        # they were returned. To make it easier to keep this promise, we
        # prohibit multiple outstanding calls to add() .
        if self.waiting:
            raise SingleFileError
        if self.failure:
            return defer.fail(self.failure)
        self.gauge += _size
        fd = defer.maybeDeferred(_func, *args, **kwargs)
        fd.addBoth(self._call_finished, _size)
        self.unflushed.addDeferred(fd)
        fd.addErrback(self._eat_pipeline_errors)
        fd.addErrback(log.err, "_eat_pipeline_errors didn't eat it")
        if self.gauge < self.capacity:
            return defer.succeed(None)
        d = defer.Deferred()
        self.waiting.append(d)
        return d

Example 41

Project: tahoe-lafs
Source File: pipeline.py
View license
    def flush(self):
        if self.failure:
            return defer.fail(self.failure)
        d, self.unflushed = self.unflushed, ExpandableDeferredList()
        d.close()
        d.addErrback(self._flushed_error)
        return d

Example 42

Project: txAMQP
Source File: server.py
View license
    def calculate(self, logid, w):
        print "calculate(logid, w) called from client"
        try:
            return self._dispatchWork(w)
        except Exception, e:
            return defer.fail(InvalidOperation(what=logid, why=e.message))

Example 43

Project: imaginary
Source File: action.py
View license
    def parse(self, player, line):
        """
        Parse an action.
        """
        for eachActionType in self.actions:
            try:
                match = eachActionType.match(player, line)
            except pyparsing.ParseException:
                pass
            else:
                if match is not None:
                    match = dict(match)
                    for k,v in match.items():
                        if isinstance(v, pyparsing.ParseResults):
                            match[k] = v[0]

                    return eachActionType().runEventTransaction(player, line, match)
        return defer.fail(eimaginary.NoSuchCommand(line))

Example 44

Project: magic-wormhole
Source File: wormhole.py
View license
    def _API_verify(self):
        if self._error: return defer.fail(self._error)
        if self._get_verifier_called: raise InternalError
        self._get_verifier_called = True
        if self._verify_result:
            return defer.succeed(self._verify_result) # bytes or Failure
        self._verifier_waiter = defer.Deferred()
        return self._verifier_waiter

Example 45

Project: magic-wormhole
Source File: wormhole.py
View license
    def _API_get(self):
        if self._error: return defer.fail(self._error)
        phase = "%d" % self._next_receive_phase
        self._next_receive_phase += 1
        with self._timing.add("API get", phase=phase):
            if phase in self._received_messages:
                return defer.succeed(self._received_messages[phase])
            d = self._receive_waiters[phase] = defer.Deferred()
            return d

Example 46

Project: ants
Source File: endpoints.py
View license
    def connect(self, protocolFactory):
        """
        Implement L{IStreamClientEndpoint.connect} to connect via TCP.
        """
        try:
            wf = _WrappingFactory(protocolFactory)
            self._reactor.connectTCP(
                self._host, self._port, wf,
                timeout=self._timeout, bindAddress=self._bindAddress)
            return wf._onConnection
        except:
            return defer.fail()

Example 47

Project: ants
Source File: endpoints.py
View license
    def connect(self, protocolFactory):
        """
        Implement L{IStreamClientEndpoint.connect} to connect with SSL over
        TCP.
        """
        try:
            wf = _WrappingFactory(protocolFactory)
            self._reactor.connectSSL(
                self._host, self._port, wf, self._sslContextFactory,
                timeout=self._timeout, bindAddress=self._bindAddress)
            return wf._onConnection
        except:
            return defer.fail()

Example 48

Project: ants
Source File: endpoints.py
View license
    def connect(self, protocolFactory):
        """
        Implement L{IStreamClientEndpoint.connect} to connect via a
        UNIX Socket
        """
        try:
            wf = _WrappingFactory(protocolFactory)
            self._reactor.connectUNIX(
                self._path, wf,
                timeout=self._timeout,
                checkPID=self._checkPID)
            return wf._onConnection
        except:
            return defer.fail()

Example 49

Project: ants
Source File: endpoints.py
View license
    def listen(self, factory):
        """
        Implement L{IStreamServerEndpoint.listen} to start listening on, and
        then close, C{self._fileno}.
        """
        if self._used:
            return defer.fail(error.AlreadyListened())
        self._used = True

        try:
            self._setNonBlocking(self.fileno)
            port = self.reactor.adoptStreamPort(
                self.fileno, self.addressFamily, factory)
            self._close(self.fileno)
        except:
            return defer.fail()
        return defer.succeed(port)

Example 50

Project: txamqp
Source File: server.py
View license
    def calculate(self, logid, w):
        print "calculate(logid, w) called from client"
        try:
            return self._dispatchWork(w)
        except Exception, e:
            return defer.fail(InvalidOperation(what=logid, why=e.message))