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


Python gen.coroutine方法代码示例

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


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

示例1: test_main

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_main(self):
        @gen.coroutine
        def main_task():
            with self.tracer.start_active_span('parent'):
                tasks = self.submit_callbacks()
                yield tasks

        with tracer_stack_context():
            self.loop.add_callback(main_task)

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) == 4)
        self.loop.start()

        spans = self.tracer.finished_spans()
        self.assertEquals(len(spans), 4)
        self.assertNamesEqual(spans, ['task', 'task', 'task', 'parent'])

        for i in range(3):
            self.assertSameTrace(spans[i], spans[-1])
            self.assertIsChildOf(spans[i], spans[-1]) 
开发者ID:opentracing,项目名称:opentracing-python,代码行数:23,代码来源:test_tornado.py

示例2: test_kv_missing

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_kv_missing(self, loop, consul_port):
        c = consul.tornado.Consul(port=consul_port)

        @gen.coroutine
        def main():
            yield c.kv.put('index', 'bump')
            index, data = yield c.kv.get('foo')
            assert data is None
            index, data = yield c.kv.get('foo', index=index)
            assert data['Value'] == six.b('bar')
            loop.stop()

        @gen.coroutine
        def put():
            yield c.kv.put('foo', 'bar')

        loop.add_timeout(time.time() + (2.0 / 100), put)
        loop.run_sync(main) 
开发者ID:poppyred,项目名称:python-consul2,代码行数:20,代码来源:test_tornado.py

示例3: test_kv_delete

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_kv_delete(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            yield c.kv.put('foo1', '1')
            yield c.kv.put('foo2', '2')
            yield c.kv.put('foo3', '3')
            index, data = yield c.kv.get('foo', recurse=True)
            assert [x['Key'] for x in data] == ['foo1', 'foo2', 'foo3']

            response = yield c.kv.delete('foo2')
            assert response is True
            index, data = yield c.kv.get('foo', recurse=True)
            assert [x['Key'] for x in data] == ['foo1', 'foo3']
            response = yield c.kv.delete('foo', recurse=True)
            assert response is True
            index, data = yield c.kv.get('foo', recurse=True)
            assert data is None
            loop.stop()

        loop.run_sync(main) 
开发者ID:poppyred,项目名称:python-consul2,代码行数:23,代码来源:test_tornado.py

示例4: test_agent_services

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_agent_services(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            services = yield c.agent.services()
            assert services == {}
            response = yield c.agent.service.register('foo')
            assert response is True
            services = yield c.agent.services()
            assert services == {'foo': {'ID': 'foo',
                                        'Service': 'foo',
                                        'Tags': [],
                                        'Meta': {},
                                        'Port': 0,
                                        'Address': '',
                                        'Weights': {'Passing': 1,
                                                    'Warning': 1},
                                        'EnableTagOverride': False}}
            response = yield c.agent.service.deregister('foo')
            assert response is True
            services = yield c.agent.services()
            assert services == {}
            loop.stop()

        loop.run_sync(main) 
开发者ID:poppyred,项目名称:python-consul2,代码行数:27,代码来源:test_tornado.py

示例5: test_root

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_root(self, loop, local_server):
        c = consul.tornado.Consul(port=local_server.port)

        @gen.coroutine
        def test_timeout():
            time_out = False
            yield sleep(loop, 20 / 1000.0)

            try:
                yield c.agent.services()
            except consul.Timeout:
                time_out = True
            assert time_out
            loop.stop()

        loop.run_sync(test_timeout) 
开发者ID:poppyred,项目名称:python-consul2,代码行数:18,代码来源:test_tornado.py

示例6: get_links_from_url

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def get_links_from_url(url):
    """Download the page at `url` and parse it for links.

    Returned links have had the fragment after `#` removed, and have been made
    absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes
    'http://www.tornadoweb.org/en/stable/gen.html'.
    """
    try:
        response = yield httpclient.AsyncHTTPClient().fetch(url)
        print('fetched %s' % url)

        html = response.body if isinstance(response.body, str) \
            else response.body.decode()
        urls = [urljoin(url, remove_fragment(new_url))
                for new_url in get_links(html)]
    except Exception as e:
        print('Exception: %s %s' % (e, url))
        raise gen.Return([])

    raise gen.Return(urls) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:22,代码来源:webspider.py

示例7: wait_for_messages

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def wait_for_messages(self, cursor=None):
        # Construct a Future to return to our caller.  This allows
        # wait_for_messages to be yielded from a coroutine even though
        # it is not a coroutine itself.  We will set the result of the
        # Future when results are available.
        result_future = Future()
        if cursor:
            new_count = 0
            for msg in reversed(self.cache):
                if msg["id"] == cursor:
                    break
                new_count += 1
            if new_count:
                result_future.set_result(self.cache[-new_count:])
                return result_future
        self.waiters.add(result_future)
        return result_future 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:chatdemo.py

示例8: authenticate_redirect

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def authenticate_redirect(self, callback_uri=None, callback=None):
        """Just like `~OAuthMixin.authorize_redirect`, but
        auto-redirects if authorized.

        This is generally the right interface to use if you are using
        Twitter for single-sign on.

        .. versionchanged:: 3.1
           Now returns a `.Future` and takes an optional callback, for
           compatibility with `.gen.coroutine`.
        """
        http = self.get_auth_http_client()
        http.fetch(self._oauth_request_token_url(callback_uri=callback_uri),
                   functools.partial(
                       self._on_request_token, self._OAUTH_AUTHENTICATE_URL,
                       None, callback)) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:18,代码来源:auth.py

示例9: release

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def release(self):
        """增加counter 并且唤醒一个waiter."""
        self._value += 1
        while self._waiters:
            waiter = self._waiters.popleft()
            if not waiter.done():
                self._value -= 1

                # If the waiter is a coroutine paused at
                #
                #     with (yield semaphore.acquire()):
                #
                # then the context manager's __exit__ calls release() at the end
                # of the "with" block.
                waiter.set_result(_ReleasingContextManager(self))
                break 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:18,代码来源:locks.py

示例10: test_async_await_mixed_multi_native_yieldpoint

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_async_await_mixed_multi_native_yieldpoint(self):
        namespace = exec_test(globals(), locals(), """
        async def f1():
            await gen.Task(self.io_loop.add_callback)
            return 42
        """)

        @gen.coroutine
        def f2():
            yield gen.Task(self.io_loop.add_callback)
            raise gen.Return(43)

        f2(callback=(yield gen.Callback('cb')))
        results = yield [namespace['f1'](), gen.Wait('cb')]
        self.assertEqual(results, [42, 43])
        self.finished = True 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:18,代码来源:gen_test.py

示例11: test_replace_yieldpoint_exception

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_replace_yieldpoint_exception(self):
        # Test exception handling: a coroutine can catch one exception
        # raised by a yield point and raise a different one.
        @gen.coroutine
        def f1():
            1 / 0

        @gen.coroutine
        def f2():
            try:
                yield f1()
            except ZeroDivisionError:
                raise KeyError()

        future = f2()
        with self.assertRaises(KeyError):
            yield future
        self.finished = True 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:20,代码来源:gen_test.py

示例12: test_swallow_yieldpoint_exception

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_swallow_yieldpoint_exception(self):
        # Test exception handling: a coroutine can catch an exception
        # raised by a yield point and not raise a different one.
        @gen.coroutine
        def f1():
            1 / 0

        @gen.coroutine
        def f2():
            try:
                yield f1()
            except ZeroDivisionError:
                raise gen.Return(42)

        result = yield f2()
        self.assertEqual(result, 42)
        self.finished = True 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:gen_test.py

示例13: test_replace_context_exception

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_replace_context_exception(self):
        # Test exception handling: exceptions thrown into the stack context
        # can be caught and replaced.
        # Note that this test and the following are for behavior that is
        # not really supported any more:  coroutines no longer create a
        # stack context automatically; but one is created after the first
        # YieldPoint (i.e. not a Future).
        @gen.coroutine
        def f2():
            (yield gen.Callback(1))()
            yield gen.Wait(1)
            self.io_loop.add_callback(lambda: 1 / 0)
            try:
                yield gen.Task(self.io_loop.add_timeout,
                               self.io_loop.time() + 10)
            except ZeroDivisionError:
                raise KeyError()

        future = f2()
        with self.assertRaises(KeyError):
            yield future
        self.finished = True 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:24,代码来源:gen_test.py

示例14: test_swallow_context_exception

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_swallow_context_exception(self):
        # Test exception handling: exceptions thrown into the stack context
        # can be caught and ignored.
        @gen.coroutine
        def f2():
            (yield gen.Callback(1))()
            yield gen.Wait(1)
            self.io_loop.add_callback(lambda: 1 / 0)
            try:
                yield gen.Task(self.io_loop.add_timeout,
                               self.io_loop.time() + 10)
            except ZeroDivisionError:
                raise gen.Return(42)

        result = yield f2()
        self.assertEqual(result, 42)
        self.finished = True 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:gen_test.py

示例15: test_py3_leak_exception_context

# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import coroutine [as 别名]
def test_py3_leak_exception_context(self):
        class LeakedException(Exception):
            pass

        @gen.coroutine
        def inner(iteration):
            raise LeakedException(iteration)

        try:
            yield inner(1)
        except LeakedException as e:
            self.assertEqual(str(e), "1")
            self.assertIsNone(e.__context__)

        try:
            yield inner(2)
        except LeakedException as e:
            self.assertEqual(str(e), "2")
            self.assertIsNone(e.__context__)

        self.finished = True 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:23,代码来源:gen_test.py


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