当前位置: 首页>>代码示例>>Python>>正文


Python defer.inlineCallbacks方法代码示例

本文整理汇总了Python中twisted.internet.defer.inlineCallbacks方法的典型用法代码示例。如果您正苦于以下问题:Python defer.inlineCallbacks方法的具体用法?Python defer.inlineCallbacks怎么用?Python defer.inlineCallbacks使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.internet.defer的用法示例。


在下文中一共展示了defer.inlineCallbacks方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_catalog

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def test_catalog(self, consul_port):
        c = consul.twisted.Consul(port=consul_port)

        @defer.inlineCallbacks
        def register():
            response = yield c.catalog.register('n1', '10.1.10.11')
            assert response is True
            yield sleep(50 / 1000.0)
            response = yield c.catalog.deregister('n1')
            assert response is True

        reactor.callLater(1.0 / 100, register)

        index, nodes = yield c.catalog.nodes()
        assert len(nodes) == 1
        current = nodes[0]

        index, nodes = yield c.catalog.nodes(index=index)
        nodes.remove(current)
        assert [x['Node'] for x in nodes] == ['n1']

        index, nodes = yield c.catalog.nodes(index=index)
        nodes.remove(current)
        assert [x['Node'] for x in nodes] == [] 
开发者ID:poppyred,项目名称:python-consul2,代码行数:26,代码来源:test_twisted.py

示例2: cache

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def cache(f):
    @wraps(f)
    @defer.inlineCallbacks
    def wrapper(*args, **kwargs):
        if 'cache_key' in kwargs and 'cache_ttl' in kwargs:
            key = "%s%s" % (f, kwargs['cache_key'])
            ttl = kwargs['cache_ttl']
            del kwargs['cache_key']
            del kwargs['cache_ttl']
            now = reactor.seconds()

            @defer.inlineCallbacks
            def get_value():
                result = yield f(*args, **kwargs)
                defer.returnValue(result)
            timestamp, result = CACHE.get(key, (0, None))
            if timestamp + ttl < now:
                CACHE[key] = (now, result)
                result = yield get_value()
                CACHE[key] = (now, result)
        else:
            result = yield f(*args, **kwargs)
        defer.returnValue(result)
    return wrapper 
开发者ID:moira-alert,项目名称:worker,代码行数:26,代码来源:cache.py

示例3: test_retry_with_twisted

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def test_retry_with_twisted(mock_client, mock_response):
    from twisted.internet import defer

    @defer.inlineCallbacks
    def return_response():
        yield
        defer.returnValue(mock_response)

    # Setup
    mock_response.with_json({"id": 123, "name": "prkumar"})
    mock_client.with_side_effect([Exception, return_response()])
    mock_client.with_io(io.TwistedStrategy())
    github = GitHub(base_url=BASE_URL, client=mock_client)

    # Run
    response = yield github.get_user("prkumar")

    assert len(mock_client.history) == 2
    assert response.json() == {"id": 123, "name": "prkumar"} 
开发者ID:prkumar,项目名称:uplink,代码行数:21,代码来源:test_retry.py

示例4: test_retry_fail_with_twisted

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def test_retry_fail_with_twisted(mock_client, mock_response):
    from twisted.internet import defer

    @defer.inlineCallbacks
    def return_response():
        yield
        defer.returnValue(mock_response)

    # Setup
    CustomException = type("CustomException", (Exception,), {})
    mock_response.with_json({"id": 123, "name": "prkumar"})
    mock_client.with_side_effect(
        [Exception, CustomException, return_response()]
    )
    mock_client.with_io(io.TwistedStrategy())
    github = GitHub(base_url=BASE_URL, client=mock_client)

    # Run
    with pytest.raises(CustomException):
        yield github.get_user("prkumar")

    assert len(mock_client.history) == 2 
开发者ID:prkumar,项目名称:uplink,代码行数:24,代码来源:test_retry.py

示例5: test_returnWithValue

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def test_returnWithValue(self):
        """
        If the C{return} statement has a value it is propagated back to the
        L{Deferred} that the C{inlineCallbacks} function returned.
        """
        environ = {"inlineCallbacks": inlineCallbacks}
        exec("""
@inlineCallbacks
def f(d):
    yield d
    return 14
        """, environ)
        d1 = Deferred()
        d2 = environ["f"](d1)
        d1.callback(None)
        self.assertEqual(self.successResultOf(d2), 14) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:18,代码来源:test_inlinecb.py

示例6: assertMistakenMethodWarning

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def assertMistakenMethodWarning(self, resultList):
        """
        Flush the current warnings and assert that we have been told that
        C{mistakenMethod} was invoked, and that the result from the Deferred
        that was fired (appended to the given list) is C{mistakenMethod}'s
        result.  The warning should indicate that an inlineCallbacks function
        called 'inline' was made to exit.
        """
        self.assertEqual(resultList, [1])
        warnings = self.flushWarnings(offendingFunctions=[self.mistakenMethod])
        self.assertEqual(len(warnings), 1)
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]['message'],
            "returnValue() in 'mistakenMethod' causing 'inline' to exit: "
            "returnValue should only be invoked by functions decorated with "
            "inlineCallbacks") 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:19,代码来源:test_inlinecb.py

示例7: test_returnValueNonLocalDeferred

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
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) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:20,代码来源:test_inlinecb.py

示例8: test_inlineCallbacksTracebacks

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def test_inlineCallbacksTracebacks(self):
        """
        L{defer.inlineCallbacks} that re-raise tracebacks into their deferred
        should not lose their tracebacks.
        """
        f = getDivisionFailure()
        d = defer.Deferred()
        try:
            f.raiseException()
        except:
            d.errback()

        def ic(d):
            yield d
        ic = defer.inlineCallbacks(ic)
        newFailure = self.failureResultOf(d)
        tb = traceback.extract_tb(newFailure.getTracebackObject())

        self.assertEqual(len(tb), 2)
        self.assertIn('test_defer', tb[0][0])
        self.assertEqual('test_inlineCallbacksTracebacks', tb[0][2])
        self.assertEqual('f.raiseException()', tb[0][3])
        self.assertIn('test_defer', tb[1][0])
        self.assertEqual('getDivisionFailure', tb[1][2])
        self.assertEqual('1/0', tb[1][3]) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:27,代码来源:test_defer.py

示例9: test_deferredGeneratorDeprecated

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def test_deferredGeneratorDeprecated(self):
        """
        L{deferredGenerator} is deprecated.
        """
        @deferredGenerator
        def decoratedFunction():
            yield None

        warnings = self.flushWarnings([self.test_deferredGeneratorDeprecated])
        self.assertEqual(len(warnings), 1)
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]['message'],
            "twisted.internet.defer.deferredGenerator was deprecated in "
            "Twisted 15.0.0; please use "
            "twisted.internet.defer.inlineCallbacks instead") 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:18,代码来源:test_defgen.py

示例10: run

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def run():
    configure_logging()
    # importing project settings for further usage
    # mainly because of the middlewares
    settings = get_project_settings()
    runner = CrawlerRunner(settings)

    # running spiders sequentially (non-distributed)
    @defer.inlineCallbacks
    def crawl():
        yield runner.crawl(IPTesterSpider)
        yield runner.crawl(UATesterSpider)
        reactor.stop()

    crawl()
    reactor.run() # block until the last call 
开发者ID:matejbasic,项目名称:PythonScrapyBasicSetup,代码行数:18,代码来源:run.py

示例11: get_height_rel_highest_func

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def get_height_rel_highest_func(bitcoind, factory, best_block_func, net):
    if '\ngetblock ' in (yield deferral.retry()(bitcoind.rpc_help)()):
        @deferral.DeferredCacher
        @defer.inlineCallbacks
        def height_cacher(block_hash):
            try:
                x = yield bitcoind.rpc_getblock('%x' % (block_hash,))
            except jsonrpc.Error_for_code(-5): # Block not found
                if not p2pool.DEBUG:
                    raise deferral.RetrySilentlyException()
                else:
                    raise
            defer.returnValue(x['blockcount'] if 'blockcount' in x else x['height'])
        best_height_cached = variable.Variable((yield deferral.retry()(height_cacher)(best_block_func())))
        def get_height_rel_highest(block_hash):
            this_height = height_cacher.call_now(block_hash, 0)
            best_height = height_cacher.call_now(best_block_func(), 0)
            best_height_cached.set(max(best_height_cached.value, this_height, best_height))
            return this_height - best_height_cached.value
    else:
        get_height_rel_highest = HeightTracker(best_block_func, factory, 5*net.SHARE_PERIOD*net.CHAIN_LENGTH/net.PARENT.BLOCK_PERIOD).get_height_rel_highest
    defer.returnValue(get_height_rel_highest) 
开发者ID:donSchoe,项目名称:p2pool-n,代码行数:24,代码来源:height_tracker.py

示例12: assertMistakenMethodWarning

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def assertMistakenMethodWarning(self, resultList):
        """
        Flush the current warnings and assert that we have been told that
        C{mistakenMethod} was invoked, and that the result from the Deferred
        that was fired (appended to the given list) is C{mistakenMethod}'s
        result.  The warning should indicate that an inlineCallbacks function
        called 'inline' was made to exit.
        """
        self.assertEqual(resultList, [1])
        warnings = self.flushWarnings(offendingFunctions=[self.mistakenMethod])
        self.assertEqual(len(warnings), 1)
        self.assertEquals(warnings[0]['category'], DeprecationWarning)
        self.assertEquals(
            warnings[0]['message'],
            "returnValue() in 'mistakenMethod' causing 'inline' to exit: "
            "returnValue should only be invoked by functions decorated with "
            "inlineCallbacks") 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:19,代码来源:inlinecb_tests.py

示例13: test_returnValueNonLocalDeferred

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
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.assertEquals(results, [])
        cause.callback(1)
        self.assertMistakenMethodWarning(results) 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:20,代码来源:inlinecb_tests.py

示例14: initialize

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def initialize():
    args = arguments.parse_maintenance_args()

    logger.init(debug=args.debug)

    @defer.inlineCallbacks
    def _run():
        leap_session = yield initialize_leap_single_user(
            args.leap_provider_cert,
            args.leap_provider_cert_fingerprint,
            args.credentials_file,
            leap_home=args.leap_home)

        execute_command(args, leap_session)

    reactor.callWhenRunning(_run)
    reactor.run() 
开发者ID:pixelated,项目名称:pixelated-user-agent,代码行数:19,代码来源:maintenance.py

示例15: _eval

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import inlineCallbacks [as 别名]
def _eval(deferred, reactor):
        """Evaluate a deferred on a given reactor and return the result

        This function is safe to call with a deferred that has already been evaluated.
        """

        @defer.inlineCallbacks
        def closure():
            if deferred.called:
                result = deferred.result
            else:
                result = yield deferred

            defer.returnValue(result)

        if threading.currentThread().getName() == reactor.thread_name:
            return closure()
        else:
            return threads.blockingCallFromThread(reactor, closure)


#
# Exceptions
# 
开发者ID:digidotcom,项目名称:python-wpa-supplicant,代码行数:26,代码来源:core.py


注:本文中的twisted.internet.defer.inlineCallbacks方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。