How to use the twisted.internet.defer function in Twisted

To help you get started, we’ve selected a few Twisted examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github telepresenceio / telepresence / k8s-proxy / test_socks.py View on Github external
def resolve(self, hostname):
        """
        Resolve a hostname by looking it up in the C{names} dictionary.
        """
        try:
            return defer.succeed(self.names[hostname])
        except KeyError:
            return defer.fail(
                DNSLookupError(
                    "FakeResolverReactor couldn't find {}".format(hostname)
                )
github twisted / twisted / src / twisted / mail / pop3client.py View on Github external
S: .

        will be lead to a result of::

            | {'TOP': None,
            |  'USER': None,
            |  'SASL': ['CRAM-MD5', 'KERBEROS_V4'],
            |  'RESP-CODES': None,
            |  'LOGIN-DELAY': ['900'],
            |  'PIPELINING': None,
            |  'EXPIRE': ['60'],
            |  'UIDL': None,
            |  'IMPLEMENTATION': ['Shlemazle-Plotz-v302']}
        """
        if useCache and self._capCache is not None:
            return defer.succeed(self._capCache)

        cache = {}
        def consume(line):
            tmp = line.split()
            if len(tmp) == 1:
                cache[tmp[0]] = None
            elif len(tmp) > 1:
                cache[tmp[0]] = tmp[1:]

        def capaNotSupported(err):
            err.trap(ServerErrorResponse)
            return None

        def gotCapabilities(result):
            self._capCache = cache
            return cache
github twisted / twisted / twisted / names / common.py View on Github external
def _lookup(self, name, cls, type, timeout):
        return defer.fail(NotImplementedError("ResolverBase._lookup"))
github skyline75489 / SimpleDNS / simpledns / dnsproxy.py View on Github external
def _respond(self, name, records):
        if records:
            return defer.succeed((records, (), ()))
        return defer.fail(failure.Failure(dns.DomainError(name)))
github twisted / twisted / twisted / words / service.py View on Github external
def addUser(self, user):
        if user.name in self.users:
            return defer.fail(failure.Failure(ewords.DuplicateUser()))
        self.users[user.name] = user
        return defer.succeed(user)
github D3f0 / txscada / src / dsem / lib / sasync / search.py View on Github external
def index(self, record, document=None, section=None):
        """
        Indexes the text content of the supplied I{record} under the supplied
        I{document} and I{section} identifiers, which must be integers if
        specified.

        Returns a C{Deferred} that fires with no argument when the indexing is
        done.

        If no document is specified, the text is considered as being at the end
        of whatever has already been indexed for a default document with the
        identifier of zero. Likewise, every document (including the default)
        has a default section, also with C{ID=0}, for indexing and searching of
        records with no section specified.
        """
        return defer.succeed(None)
github D3f0 / txscada / src / dsem / lib / sasync / database.py View on Github external
d = self.getSession()
                d.addCallback(lambda _: doTransaction(True))
            else:
                d = doTransaction(False)
        elif hasattr(self, '_transactionStartupDeferred') and \
             not self._transactionStartupDeferred.called:
            # Startup is in progress, make a new Deferred to the start of the
            # transaction and chain it to the startup Deferred.
            d = defer.Deferred()
            if useSession:
                d.addCallback(lambda _: self.getSession())
            d.addCallback(lambda _: doTransaction(useSession))
            self._transactionStartupDeferred.chainDeferred(d)
        else:
            # We need to start things up before doing this first transaction
            d = defer.maybeDeferred(self.startup)
            self._transactionStartupDeferred = d
            d.addCallback(started)
            d.addCallback(lambda _: doTransaction(useSession))
        # Return whatever Deferred we've got
        return d
github buildbot / buildbot / worker / buildbot_worker / base.py View on Github external
    @defer.inlineCallbacks
    def setServiceParent(self, parent):
        yield service.Service.setServiceParent(self, parent)
        self.bot = self.parent
        # note that self.parent will go away when the buildmaster's config
github hippich / Bitcoin-Poker-Room / lib / ppn / pokernetwork / pokeravatar.py View on Github external
def longpollDeferred(self):
        self._longpoll_deferred = defer.Deferred()
        d = self.flushLongPollDeferred()
        if not d.called:
            def longPollDeferredTimeout():
                self.longPollTimer = None
                self._longpoll_deferred = None
                packets = self.resetPacketsQueue()
                if self.service.verbose > 3:
                    self.message("longPollDeferredTimeout(%s): " % str(packets))
                d.callback(packets)
            self.longPollTimer = reactor.callLater(self.service.long_poll_timeout, longPollDeferredTimeout)
        return d
github Cue / greplin-twisted-utils / src / greplin / defer / inline.py View on Github external
# arising from repeatedly yielding immediately ready deferreds.  This while
    # loop and the waiting variable solve that by manually unfolding the
    # recursion.
    while self._state != STATE_CANCELLED:
      try:
        # Send the last result back as the result of the yield expression.
        if isinstance(result, failure.Failure):
          result = result.throwExceptionIntoGenerator(self._generator)
        else:
          result = self._generator.send(result)
      except StopIteration:
        # Fell off the end, or "return" statement
        if self._state != STATE_CANCELLED:
          self.callback(None)
        return
      except defer._DefGen_Return, e: # Need to access protected member for consistency. # pylint: disable=W0212
        if self._state != STATE_CANCELLED:
          context.setCurrent(self._context)
          self.callback(e.value)
        return
      except:
        self.errback()
        return

      if self._state == STATE_NORMAL and isinstance(result, defer.Deferred):
        # A deferred was yielded, get the result.
        self._current = result
        self._state = STATE_WAITING
        cb = self._handleResult
        result.addCallbacks(cb, cb, EMPTY_TUPLE, EMPTY_TUPLE, EMPTY_DICT, EMPTY_DICT)
        if self._state == STATE_WAITING:
          # Haven't called back yet, set flag so that we get reinvoked and return from the loop.