twisted.internet.defer.returnValue

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

137 Examples 7

3 Source : twisted_test.py
with GNU General Public License v3.0
from agajdosi

    def test_success(self):
        @inlineCallbacks
        def fn():
            if False:
                # inlineCallbacks doesn't work with regular functions;
                # must have a yield even if it's unreachable.
                yield
            returnValue(42)

        res = yield fn()
        self.assertEqual(res, 42)

    @gen_test

3 Source : test_inlinecb.py
with MIT License
from autofelix

    def mistakenMethod(self):
        """
        This method mistakenly invokes L{returnValue}, despite the fact that it
        is not decorated with L{inlineCallbacks}.
        """
        returnValue(1)


    def assertMistakenMethodWarning(self, resultList):

3 Source : test_inlinecb.py
with MIT License
from autofelix

    def test_returnValueNonLocalWarning(self):
        """
        L{returnValue} will emit a non-local exit warning in the simplest case,
        where the offending function is invoked immediately.
        """
        @inlineCallbacks
        def inline():
            self.mistakenMethod()
            returnValue(2)
            yield 0
        d = inline()
        results = []
        d.addCallback(results.append)
        self.assertMistakenMethodWarning(results)


    def test_returnValueNonLocalDeferred(self):

3 Source : test_inlinecb.py
with MIT License
from autofelix

    def sampleInlineCB(self, getChildDeferred=None):
        """
        Generator for testing cascade cancelling cases.

        @param getChildDeferred: Some callable returning L{Deferred} that we
            awaiting (with C{yield})
        """
        if getChildDeferred is None:
            getChildDeferred = self.getDeferred
        try:
            x = yield getChildDeferred()
        except UntranslatedError:
            raise TranslatedError()
        except DontFail as df:
            x = df.actualValue - 2
        returnValue(x + 1)


    def getDeferred(self):

3 Source : test_defgen.py
with MIT License
from autofelix

    def _genBasics(self):

        x = yield getThing()

        self.assertEqual(x, "hi")

        try:
            yield getOwie()
        except ZeroDivisionError as e:
            self.assertEqual(str(e), 'OMG')
        returnValue("WOOSH")
    _genBasics = inlineCallbacks(_genBasics)

3 Source : test_defgen.py
with MIT License
from autofelix

    def _genStackUsage(self):
        for x in range(5000):
            # Test with yielding a deferred
            yield defer.succeed(1)
        returnValue(0)
    _genStackUsage = inlineCallbacks(_genStackUsage)

3 Source : test_defgen.py
with MIT License
from autofelix

    def _genStackUsage2(self):
        for x in range(5000):
            # Test with yielding a random value
            yield 1
        returnValue(0)
    _genStackUsage2 = inlineCallbacks(_genStackUsage2)

3 Source : test_defgen.py
with MIT License
from autofelix

    def testYieldNonDeferred(self):
        """
        Ensure that yielding a non-deferred passes it back as the
        result of the yield expression.

        @return: A L{twisted.internet.defer.Deferred}
        @rtype: L{twisted.internet.defer.Deferred}
        """
        def _test():
            yield 5
            returnValue(5)
        _test = inlineCallbacks(_test)

        return _test().addCallback(self.assertEqual, 5)

    def testReturnNoValue(self):

3 Source : test_defgen.py
with MIT License
from autofelix

    def testReturnValue(self):
        """Ensure that returnValue works."""
        def _return():
            yield 5
            returnValue(6)
        _return = inlineCallbacks(_return)

        return _return().addCallback(self.assertEqual, 6)


    def test_nonGeneratorReturn(self):

3 Source : test_defgen.py
with MIT License
from autofelix

    def test_nonGeneratorReturnValue(self):
        """
        Ensure that C{TypeError} with a message about L{inlineCallbacks} is
        raised when a non-generator calls L{returnValue}.
        """
        def _noYield():
            returnValue(5)
        _noYield = inlineCallbacks(_noYield)

        self.assertIn("inlineCallbacks",
            str(self.assertRaises(TypeError, _noYield)))



class DeprecateDeferredGeneratorTests(unittest.SynchronousTestCase):

3 Source : twisted_test.py
with Apache License 2.0
from awslabs

    def test_success(self):
        @inlineCallbacks
        def fn():
            if False:
                # inlineCallbacks doesn't work with regular functions;
                # must have a yield even if it's unreachable.
                yield
            returnValue(42)
        f = gen.convert_yielded(fn())
        self.assertEqual(f.result(), 42)

    def test_failure(self):

3 Source : helper.py
with GNU General Public License v3.0
from AXErunners

def check_block_header(bitcoind, block_hash):
    try:
        yield bitcoind.rpc_getblockheader(block_hash)
    except jsonrpc.Error_for_code(-5):
        defer.returnValue(False)
    else:
        defer.returnValue(True)

3 Source : p2p.py
with GNU General Public License v3.0
from AXErunners

    def do_ping(self):
        start = reactor.seconds()
        yield self.get_shares(hashes=[0], parents=0, stops=[])
        end = reactor.seconds()
        defer.returnValue(end - start)

class ServerFactory(protocol.ServerFactory):

3 Source : test_p2p.py
with GNU General Public License v3.0
from AXErunners

    def test_get_block(self):
        factory = p2p.ClientFactory(networks.nets['axe'])
        c = reactor.connectTCP('127.0.0.1', 9937, factory)
        try:
            h = 0x00000000000132b9afeca5e9a2fdf4477338df6dcff1342300240bc70397c4bb
            block = yield deferral.retry()(defer.inlineCallbacks(lambda: defer.returnValue((yield (yield factory.getProtocol()).get_block(h)))))()
            assert data.merkle_hash(map(data.hash256, map(data.tx_type.pack, block['txs']))) == block['header']['merkle_root']
            assert data.hash256(data.block_header_type.pack(block['header'])) == h
        finally:
            factory.stopTrying()
            c.disconnect()

3 Source : deferral.py
with GNU General Public License v3.0
from AXErunners

    def __call__(self, key):
        if key in self.waiting:
            yield self.waiting[key]
        
        if key in self.backing:
            defer.returnValue(self.backing[key])
        else:
            self.waiting[key] = defer.Deferred()
            try:
                value = yield self.func(key)
            finally:
                self.waiting.pop(key).callback(None)
        
        self.backing[key] = value
        defer.returnValue(value)
    
    _nothing = object()

3 Source : variable.py
with GNU General Public License v3.0
from AXErunners

    def get_when_satisfies(self, func):
        while True:
            if func(self.value):
                defer.returnValue(self.value)
            yield self.changed.once.get_deferred()
    
    def get_not_none(self):

3 Source : bet365.py
with MIT License
from Chiang97912

def search(league, hometeam, awayteam, score, retimeset, eventid):
    yield sleep(0.3)
    global occurred_eventids
    global checklist
    occurred_eventids.append(eventid)
    checklist[eventid] = {
        'league': league,
        'hometeam': hometeam,
        'awayteam': awayteam,
        'score': score,
        'retimeset': retimeset
    }
    print(league, hometeam, awayteam, score, retimeset, eventid)
    req = u'\x16\x006V{}C18A_1_1\x01'.format(eventid).encode('utf-8')
    returnValue(req)


class MyClientProtocol(WebSocketClientProtocol):

3 Source : twisted_defer_example.py
with GNU General Public License v3.0
from ckarageorgkaneen

def f():
    yield
    # While @inlineCallbacks did allow you to write code that was linear in
    # appearance (unlike callbacks), some hacks were required, such as this
    # call to defer.returnValue(), which is how you have to return values from
    # @inlineCallbacks coroutines.
    defer.returnValue(123)


@defer.inlineCallbacks

3 Source : snippet.py
with Apache License 2.0
from dockerizeme

    def _get_ip_addr(self, hostname, timeout):
        ip = yield self.redis.get(hostname)
        log.msg('redis: %s'% ip)
        r = None
        if ip:
            defer.returnValue([(dns.RRHeader(hostname, dns.A, dns.IN, self.ttl, dns.Record_A(ip, self.ttl)),), (), ()])
        else:
            i = yield self._lookup(hostname, dns.IN, dns.A, timeout)
            defer.returnValue(i)
        
    def lookupAddress(self, name, timeout = None):

3 Source : snippet.py
with Apache License 2.0
from dockerizeme

    def start_instance(self, build):
        log.msg("Attempting to start '%s'" % self.name)
        retval = yield utils.getProcessValue(self.start_script[0], self.start_script[1:])
        defer.returnValue(retval == 0)

    @defer.inlineCallbacks

3 Source : snippet.py
with Apache License 2.0
from dockerizeme

    def stop_instance(self, fast=False):
        log.msg("Attempting to stop '%s'" % self.name)
        retval = yield utils.getProcessValue(self.stop_script[0], self.stop_script[1:])

        log.msg("subordinate destroyed (%s): Forcing its connection closed." % self.name)
        yield AbstractBuildSlave.disconnect(self)

        log.msg("We forced disconnection (%s), cleaning up and triggering new build" % self.name)
        self.botmain.maybeStartBuildsForSlave(self.name)

        defer.returnValue(retval == 0)

3 Source : test_inlinecb.py
with MIT License
from fbla-competitive-events

    def test_returnValueNonLocalDeferred(self):
        """
        L{returnValue} will emit a non-local warning in the case where the
        L{inlineCallbacks}-decorated function has already yielded a Deferred
        and therefore moved its generator function along.
        """
        cause = Deferred()
        @inlineCallbacks
        def inline():
            yield cause
            self.mistakenMethod()
            returnValue(2)
        effect = inline()
        results = []
        effect.addCallback(results.append)
        self.assertEqual(results, [])
        cause.callback(1)
        self.assertMistakenMethodWarning(results)


3 Source : protocol.py
with GNU General Public License v2.0
from fedora-infra

    def declare_queue(self, queue):
        """
        Declare a queue. This is a convenience method to call :meth:`declare_queues` with a single
        argument.
        """
        names = yield self.declare_queues([queue])
        defer.returnValue(names[0])

    @defer.inlineCallbacks

3 Source : hgpoller.py
with GNU General Public License v2.0
from flathub

    def _getRevNodeList(self, revset):
        revListArgs = ['log', '-r', revset, r'--template={rev}:{node}\n']
        results = yield utils.getProcessOutput(self.hgbin, revListArgs,
                                               path=self._absWorkdir(), env=os.environ,
                                               errortoo=False)
        results = results.decode(self.encoding)

        revNodeList = [rn.split(':', 1) for rn in results.strip().split()]
        defer.returnValue(revNodeList)

    @defer.inlineCallbacks

3 Source : builds.py
with GNU General Public License v2.0
from flathub

    def setBuildFlathubName(self, buildid, name):
        res = yield self.master.db.builds.setBuildFlathubName(
            buildid=buildid, name=name)
        yield self.generateEvent(buildid, "update")
        defer.returnValue(res)

    @base.updateMethod

3 Source : builds.py
with GNU General Public License v2.0
from flathub

    def setBuildFlathubRepoId(self, buildid, repo_id):
        res = yield self.master.db.builds.setBuildFlathubRepoId(
            buildid=buildid, repo_id=repo_id)
        yield self.generateEvent(buildid, "update")
        defer.returnValue(res)

    @base.updateMethod

3 Source : builds.py
with GNU General Public License v2.0
from flathub

    def setBuildFlathubRepoStatus(self, buildid, repo_status):
        res = yield self.master.db.builds.setBuildFlathubRepoStatus(
            buildid=buildid, repo_status=repo_status)
        yield self.generateEvent(buildid, "update")
        defer.returnValue(res)

    @base.updateMethod

3 Source : builds.py
with GNU General Public License v2.0
from flathub

    def setBuildFlathubBuildType(self, buildid, build_type):
        res = yield self.master.db.builds.setBuildFlathubBuildType(
            buildid=buildid, build_type=build_type)
        yield self.generateEvent(buildid, "update")
        defer.returnValue(res)

    @base.updateMethod

3 Source : flathub_master.py
with GNU General Public License v2.0
from flathub

    def run(self):
        log = yield self.addLog('log')
        if not reload_builds ():
            log.addStderr('Failed to update the builds.json config, ping the admins')
            defer.returnValue(FAILURE)
            return

        log.finish()

        defer.returnValue(SUCCESS)

class MaybeAddSteps(steps.BuildStep):

3 Source : flathub_master.py
with GNU General Public License v2.0
from flathub

def githubApiRequest(path):
    session = requests.Session()
    res = yield session.get(GITHUB_API_BASE + path,
                            headers={
                                "Authorization": "token  " + config.github_api_token
                            })
    defer.returnValue(res)

@defer.inlineCallbacks

3 Source : flathub_master.py
with GNU General Public License v2.0
from flathub

def githubApiPostComment(issue_url, comment):
    session = requests.Session()
    if config.comment_prefix_text:
        comment = config.comment_prefix_text + "\n\n" + comment
    res = yield session.post(issue_url + "/comments",
                             headers={
                                 "Authorization": "token  " + config.github_api_token
                             },
                             json= {
                                 'body': comment
                             })
    defer.returnValue(res)

@defer.inlineCallbacks

3 Source : flathub_master.py
with GNU General Public License v2.0
from flathub

    def assertUserMaintainsBuild(self, build_id, userDetails):
        build = yield self.master.data.get(("builds", build_id))
        buildrequest = yield self.master.data.get(('buildrequests', build['buildrequestid']))
        buildset = yield self.master.data.get(("buildsets", buildrequest['buildsetid']))
        repo = buildset['sourcestamps'][0]['repository']
        yield githubApiAssertUserMaintainsRepo(repo, userDetails)
        defer.returnValue(None)

    @defer.inlineCallbacks

3 Source : flathub_master.py
with GNU General Public License v2.0
from flathub

    def assertUserAllowed(self, ep, action, options, userDetails):
        if len(ep) == 2 and ep[0] == 'builds' and (action == u'publish' or action == u'delete' or action == u'rebuild' or action == u'stop'):
            yield self.assertUserMaintainsBuild(ep[1], userDetails)
            defer.returnValue(None)

        if len(ep) == 2 and ep[0] == 'forceschedulers' and ep[1] == 'build-app' and action == u'force':
            git_repo_uri = options[u'Override git repo_repository']
            git_branch = options[u'Override git repo_branch']
            buildname = options[u'buildname']
            data = builds.lookup_by_git_and_name(git_repo_uri, git_branch, buildname)
            flathub_git_repo = data.get_flathub_repo_uri()
            yield githubApiAssertUserMaintainsRepo(flathub_git_repo, userDetails)
            defer.returnValue(None)

        yield authz.Authz.assertUserAllowed(self, ep, action, options, userDetails)

class AppParameter(util.CodebaseParameter):

3 Source : flathub_master.py
with GNU General Public License v2.0
from flathub

    def run(self):
        build = self.build
        props = build.properties
        flathub_issue_url = props.getProperty('flathub_issue_url', None)
        if flathub_issue_url:
            builderid = yield build.getBuilderId()
            if flathub_issue_url and config.github_api_token:
                githubApiPostComment(flathub_issue_url, "Started [test build %d](%s#/builders/%d/builds/%d)" % (build.number, config.buildbot_uri, builderid, build.number))

        defer.returnValue(buildbot.process.results.SUCCESS)

class FlathubEndCommentStep(steps.BuildStep, CompositeStepMixin):

3 Source : generic.py
with GNU General Public License v2.0
from flathub

    def perform(self, manager):
        if self._sshKey is not None or self._sshHostKey is not None:
            with private_tempdir.PrivateTemporaryDirectory(
                    prefix='ssh-', dir=manager.master.basedir) as temp_dir:

                key_path, hosts_path = yield self._prepareSshKeys(manager,
                                                                  temp_dir)

                ret = yield self._performImpl(manager, key_path, hosts_path)
        else:
            ret = yield self._performImpl(manager, None, None)
        defer.returnValue(ret)


@implementer(IMachineAction)

3 Source : kubeclientservice.py
with GNU General Public License v2.0
from flathub

    def getAuthorization(self):
        if self.basicAuth is not None:
            basicAuth = yield self.renderSecrets(self.basicAuth)
            authstring = "{user}:{password}".format(**basicAuth).encode('utf-8')
            encoded = base64.b64encode(authstring)
            return defer.returnValue("Basic {0}".format(encoded))

        if self.bearerToken is not None:
            bearerToken = yield self.renderSecrets(self.bearerToken)
            return defer.returnValue("Bearer {0}".format(bearerToken))

        return defer.returnValue(None)

    def getConfig(self):

3 Source : kubeclientservice.py
with GNU General Public License v2.0
from flathub

    def createPod(self, namespace, spec):
        url = '/api/v1/namespaces/{namespace}/pods'.format(namespace=namespace)
        res = yield self.post(url, json=spec)
        res_json = yield res.json()
        if res.code not in (200, 201, 202):
            raise KubeError(res_json)
        defer.returnValue(res_json)

    @defer.inlineCallbacks

3 Source : kubeclientservice.py
with GNU General Public License v2.0
from flathub

    def deletePod(self, namespace, name, graceperiod=0):
        url = '/api/v1/namespaces/{namespace}/pods/{name}'.format(
            namespace=namespace, name=name)
        res = yield self.delete(url, params={'graceperiod': graceperiod})
        res_json = yield res.json()
        if res.code != 200:
            raise KubeError(res_json)
        defer.returnValue(res_json)

    @defer.inlineCallbacks

3 Source : kubeclientservice.py
with GNU General Public License v2.0
from flathub

    def waitForPodDeletion(self, namespace, name, timeout):
        t1 = time.time()
        url = '/api/v1/namespaces/{namespace}/pods/{name}/status'.format(
            namespace=namespace, name=name)
        while True:
            if time.time() - t1 > timeout:
                raise TimeoutError(
                    "Did not see pod {name} terminate after {timeout}s".format(
                        name=name, timeout=timeout))
            res = yield self.get(url)
            res_json = yield res.json()
            if res.code == 404:
                break  # 404 means the pod has terminated
            if res.code != 200:
                raise KubeError(res_json)
            yield asyncSleep(1)
        defer.returnValue(res_json)

    @property

3 Source : latent.py
with GNU General Public License v2.0
from flathub

    def renderWorkerPropsOnStart(self, build):
        props = yield self.renderWorkerProps(build)
        self._actual_build_props = copy.deepcopy(props)
        defer.returnValue(props)

    def resetWorkerPropsOnStop(self):

3 Source : latent.py
with GNU General Public License v2.0
from flathub

    def isCompatibleWithBuild(self, build):
        if self._actual_build_props is None:
            defer.returnValue(True)

        requested_props = yield self.renderWorkerProps(build)

        defer.returnValue(requested_props == self._actual_build_props)

3 Source : docker.py
with GNU General Public License v2.0
from flathub

    def start_instance(self, build):
        if self.instance is not None:
            raise ValueError('instance active')
        image, dockerfile, volumes, custom_context, encoding, buildargs = \
            yield self.renderWorkerPropsOnStart(build)

        res = yield threads.deferToThread(self._thd_start_instance, image,
                                          dockerfile, volumes, custom_context,
                                          encoding, buildargs)
        defer.returnValue(res)

    def _image_exists(self, client, name):

3 Source : kubernetes.py
with GNU General Public License v2.0
from flathub

    def start_instance(self, build):
        yield self.stop_instance(reportFailure=False)
        pod_spec = yield self.renderWorkerPropsOnStart(build)
        try:
            yield self._kube.createPod(self.namespace, pod_spec)
        except kubeclientservice.KubeError as e:
            raise LatentWorkerFailedToSubstantiate(str(e)) from e
        defer.returnValue(True)

    @defer.inlineCallbacks

3 Source : fs.py
with GNU General Public License v2.0
from flathub

    def _clobber(self, dummy, chmodDone=False):
        command = ["rm", "-rf", self.dir]
        c = runprocess.RunProcess(self.builder, command, self.builder.basedir,
                                  sendRC=0, timeout=self.timeout, maxTime=self.maxTime,
                                  logEnviron=self.logEnviron, usePTY=False)

        self.command = c
        # sendRC=0 means the rm command will send stdout/stderr to the
        # master, but not the rc=0 when it finishes. That job is left to
        # _sendRC
        rc = yield c.start()
        # The rm -rf may fail if there is a left-over subdir with chmod 000
        # permissions. So if we get a failure, we attempt to chmod suitable
        # permissions and re-try the rm -rf.
        if not chmodDone:
            rc = yield self._tryChmod(rc)
        defer.returnValue(rc)

    @defer.inlineCallbacks

3 Source : test_bot_Worker.py
with GNU General Public License v2.0
from flathub

    def requestAvatar(self, avatarId, mind, *interfaces):
        assert pb.IPerspective in interfaces
        self.mind = mind
        self.perspective.mind = mind
        if self.on_attachment:
            yield self.on_attachment(mind)

        defer.returnValue((pb.IPerspective, self.perspective, lambda: None))

    def shutdown(self):

3 Source : __init__.py
with GNU General Public License v2.0
from flathub

    def getPng(self, request, builder):
        svg = yield self.getSvg(request, builder)
        request.setHeader('content-type', 'image/png')
        defer.returnValue(cairosvg.svg2png(svg))

    @app.route("/  <  string:builder>.svg", methods=['GET'])

3 Source : dns.py
with MIT License
from jesopo

    def check(self, scan, env):
        query = ip_address(scan.ip).reverse_pointer
        try:
            result, _, _ = yield env.resolver.lookupPointer(query)
        except (DNSLookupError, DNSNameError):
            # XXX is this the right set of exceptions?
            defer.returnValue(None)
        else:
            # domain names should always be ascii, yeah?
            result = result[0].payload.name.name.decode("ascii")
            for pattern, description in self.bad:
                if pattern.fullmatch(result):
                    defer.returnValue(description)
                    break

class DNSBLChecker(object):

3 Source : step_source.py
with MIT License
from lab132

    def _fetch(self, arg):
        res = yield super(Gitea, self)._fetch(arg)
        if self.build.hasProperty("pr_id"):
            remote = yield self._dovccmd(
                ['config', 'remote.pr_source.url'], collectStdout=True, abandonOnFailure=False)
            if remote is None or remote.strip() is '':
                yield self._dovccmd(
                    ['remote', 'add', 'pr_source',
                     self.build.getProperty("head_git_ssh_url", None)])
            else:
                yield self._dovccmd(
                    ['remote', 'set-url', 'pr_source',
                     self.build.getProperty("head_git_ssh_url", None)])
            yield self._dovccmd(['fetch', 'pr_source'])
            res = yield self._dovccmd(['merge', self.build.getProperty("head_sha", None)])
        defer.returnValue(res)

3 Source : test_reporter.py
with MIT License
from lab132

    def setupBuildResults(self, buildResults):
        self.insertTestData([buildResults], buildResults)
        build = yield self.master.data.get(("builds", 20))
        defer.returnValue(build)

    @defer.inlineCallbacks

3 Source : test_web.py
with MIT License
from magic-wormhole

    def make_client(self):
        f = WSFactory(self.relayurl)
        f.d = defer.Deferred()
        reactor.connectTCP("127.0.0.1", self.rdv_ws_port, f)
        c = yield f.d
        self._clients.append(c)
        returnValue(c)

    @inlineCallbacks

See More Examples