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


Python asyncio.coroutine方法代码示例

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


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

示例1: run_sync

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def run_sync(func: Callable[..., Any]) -> Callable[..., Coroutine[Any, None, None]]:
    """Ensure that the sync function is run within the event loop.

    If the *func* is not a coroutine it will be wrapped such that
    it runs in the default executor (use loop.set_default_executor
    to change). This ensures that synchronous functions do not
    block the event loop.
    """

    @wraps(func)
    async def _wrapper(*args: Any, **kwargs: Any) -> Any:
        loop = asyncio.get_running_loop()
        result = await loop.run_in_executor(
            None, copy_context().run, partial(func, *args, **kwargs)
        )
        if isgenerator(result):
            return run_sync_iterable(result)  # type: ignore
        else:
            return result

    _wrapper._quart_async_wrapper = True  # type: ignore
    return _wrapper 
开发者ID:pgjones,项目名称:quart,代码行数:24,代码来源:utils.py

示例2: test_retry_with_asyncio

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def test_retry_with_asyncio(mock_client, mock_response):
    import asyncio

    @asyncio.coroutine
    def coroutine():
        return mock_response

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

    # Run
    awaitable = github.get_user("prkumar")
    loop = asyncio.get_event_loop()
    response = loop.run_until_complete(asyncio.ensure_future(awaitable))

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

示例3: test_request_send

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def test_request_send(self, mocker, aiohttp_session_mock):
        # Setup
        import asyncio

        expected_response = mocker.Mock()

        @asyncio.coroutine
        def request(*args, **kwargs):
            return expected_response

        aiohttp_session_mock.request = request
        client = aiohttp_.AiohttpClient(aiohttp_session_mock)

        # Run
        response = client.send((1, 2, {}))
        loop = asyncio.get_event_loop()
        value = loop.run_until_complete(asyncio.ensure_future(response))

        # Verify
        assert value == expected_response 
开发者ID:prkumar,项目名称:uplink,代码行数:22,代码来源:test_clients.py

示例4: test_wrap_callback

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def test_wrap_callback(self, mocker):
        import asyncio

        # Setup
        c = AiohttpClient()
        mocker.spy(c, "_sync_callback_adapter")

        # Run: with callback that is not a coroutine
        def callback(*_):
            pass

        c.wrap_callback(callback)

        # Verify: Should wrap it
        c._sync_callback_adapter.assert_called_with(callback)

        # Run: with coroutine callback
        coroutine_callback = asyncio.coroutine(callback)
        assert c.wrap_callback(coroutine_callback) is coroutine_callback 
开发者ID:prkumar,项目名称:uplink,代码行数:21,代码来源:test_clients.py

示例5: test_threaded_response

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def test_threaded_response(self, mocker):
        # Setup
        import asyncio

        @asyncio.coroutine
        def coroutine():
            return 1

        def not_a_coroutine():
            return 2

        response = mocker.Mock()
        response.coroutine = coroutine
        response.not_coroutine = not_a_coroutine
        threaded_response = aiohttp_.ThreadedResponse(response)

        # Run
        threaded_coroutine = threaded_response.coroutine
        return_value = threaded_coroutine()

        # Verify
        assert isinstance(threaded_coroutine, aiohttp_.ThreadedCoroutine)
        assert return_value == 1
        assert threaded_response.not_coroutine is not_a_coroutine 
开发者ID:prkumar,项目名称:uplink,代码行数:26,代码来源:test_clients.py

示例6: create

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def create(cls, *args, **kwargs):
        """
        Builds a client instance with
        :py:class:`aiohttp.ClientSession` arguments.

        Instead of directly initializing this class with a
        :py:class:`aiohttp.ClientSession`, use this method to have the
        client lazily construct a session when sending the first
        request. Hence, this method guarantees that the creation of the
        underlying session happens inside of a coroutine.

        Args:
            *args: positional arguments that
                :py:class:`aiohttp.ClientSession` takes.
            **kwargs: keyword arguments that
                :py:class:`aiohttp.ClientSession` takes.
        """
        session_build_args = cls._create_session(*args, **kwargs)
        return AiohttpClient(session=session_build_args) 
开发者ID:prkumar,项目名称:uplink,代码行数:21,代码来源:aiohttp_.py

示例7: test_run_hub

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def test_run_hub(self, data):

        Hub.hubs = []
        sensor_name = 'sensor'
        sensor = data.draw(st.sampled_from(self.sensor_list))
        capabilities = self._draw_capabilities(data, sensor)

        hub_type = data.draw(st.sampled_from(self.hub_list))
        TestHub, stop_evt = self._get_hub_class(hub_type, sensor, sensor_name, capabilities)
        hub = TestHub('test_hub')

        # Start the hub
        #kernel.run(self._emit_control(TestHub))
        with patch('Adafruit_BluefruitLE.get_provider') as ble,\
             patch('bricknil.ble_queue.USE_BLEAK', False) as use_bleak:
            ble.return_value = MockBLE(hub)
            sensor_obj = getattr(hub, sensor_name)
            sensor_obj.send_message = Mock(side_effect=coroutine(lambda x,y: "the awaitable should return this"))
            kernel.run(self._emit_control, data, hub, stop_evt, ble(), sensor_obj)
            #start(system) 
开发者ID:virantha,项目名称:bricknil,代码行数:22,代码来源:test_hub.py

示例8: emulate

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def emulate(self, *coroutines: Iterable[asyncio.coroutine]):
        """ Convenience method that runs a full method in a blocking manner.
        Performs connect, run, and then disconnect.

        Parameters:
            *coroutines -- any asyncio coroutines to be executed concurrently
                           with our emulation
        """

        self.connect()

        try:
            self.run_with(*coroutines)
        except KeyboardInterrupt:
            pass
        finally:
            self.disconnect()


    #
    # I/O interface.
    # 
开发者ID:usb-tools,项目名称:Facedancer,代码行数:24,代码来源:device.py

示例9: async_test

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def async_test(func):
    @functools.wraps(func)
    def _async_test(*args, **kw):
        cofunc = asyncio.coroutine(func)
        oldloop = asyncio.get_event_loop()
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.set_debug(True)
        console = SharedConsole(interval=0)
        results = SharedCounters(
            "WORKER", "REACHED", "RATIO", "OK", "FAILED", "MINUTE_OK", "MINUTE_FAILED"
        )
        kw["loop"] = loop
        kw["console"] = console
        kw["results"] = results
        try:
            loop.run_until_complete(cofunc(*args, **kw))
        finally:
            loop.stop()
            loop.close()
            asyncio.set_event_loop(oldloop)

    return _async_test 
开发者ID:loads,项目名称:molotov,代码行数:25,代码来源:support.py

示例10: _connect

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def _connect(self):
        """
            Connect to the stream

        Returns
        -------
        asyncio.coroutine
            The streaming response
        """
        logger.debug("connecting to the stream")
        await self.client.setup
        if self.session is None:
            self.session = self.client._session
        kwargs = await self.client.headers.prepare_request(**self.kwargs)
        request = self.client.error_handler(self.session.request)

        return await request(timeout=0, **kwargs) 
开发者ID:odrling,项目名称:peony-twitter,代码行数:19,代码来源:stream.py

示例11: test_changes_continuous_reading

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def test_changes_continuous_reading(self):
        ids = [utils.uuid() for _ in range(3)]

        @asyncio.coroutine
        def task():
            for idx in ids:
                yield from self.db[idx].update({})
        asyncio.Task(task())

        with (yield from self.db.changes(feed='continuous',
                                         timeout=1000)) as feed:

            while True:
                self.assertTrue(feed.is_active())
                event = yield from feed.next()
                if event is None:
                    break
                self.assertIsInstance(event, dict)
                self.assertIn(event['id'], ids)

            self.assertFalse(feed.is_active()) 
开发者ID:aio-libs,项目名称:aiocouchdb,代码行数:23,代码来源:test_database.py

示例12: test_changes_eventsource

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def test_changes_eventsource(self):
        ids = [utils.uuid() for _ in range(3)]

        @asyncio.coroutine
        def task():
            for idx in ids:
                yield from self.db[idx].update({})
        asyncio.Task(task())

        with (yield from self.db.changes(feed='eventsource',
                                         timeout=1000)) as feed:

            while True:
                self.assertTrue(feed.is_active())
                event = yield from feed.next()
                if event is None:
                    break
                self.assertIsInstance(event, dict)
                self.assertIn(event['id'], ids) 
开发者ID:aio-libs,项目名称:aiocouchdb,代码行数:21,代码来源:test_database.py

示例13: load_events

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def load_events(self):
        """Load more events for this conversation (coroutine)"""
        # Don't try to load while we're already loading.
        if not self.is_loading and not self.first_loaded:
            logger.debug('Loading more conversation events')

            self.is_loading = True

            try:
                conv_events = yield from self.conv.get_events(self.conv.events[0].id_)
            except (IndexError, hangups.NetworkError):
                conv_events = []

            if conv_events:
                self.scroll_prev_height = self.messagesWebView.page().mainFrame().contentsSize().height()
            else:
                self.first_loaded = True

            for event in reversed(conv_events):
                self.on_event(event, set_title=False, set_unread=False, prepend=True)

            self.is_loading = False 
开发者ID:xmikos,项目名称:qhangups,代码行数:24,代码来源:conversationwidget.py

示例14: _do_heartbeat

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def _do_heartbeat(self):
        while True:
            try:
                if self._socket.getsockopt(zmq.TYPE) == zmq.ROUTER:
                    yield from self._do_router_heartbeat()
                elif self._socket.getsockopt(zmq.TYPE) == zmq.DEALER:
                    yield from self._do_dealer_heartbeat()
                yield from asyncio.sleep(self._heartbeat_interval,
                                         loop=self._event_loop)
            except CancelledError:  # pylint: disable=try-except-raise
                # The concurrent.futures.CancelledError is caught by asyncio
                # when the Task associated with the coroutine is cancelled.
                # The raise is required to stop this component.
                raise
            except Exception as e:  # pylint: disable=broad-except
                LOGGER.exception(
                    "An error occurred while sending heartbeat: %s", e) 
开发者ID:hyperledger,项目名称:sawtooth-core,代码行数:19,代码来源:interconnect.py

示例15: test_wait_ping

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import coroutine [as 别名]
def test_wait_ping(echo):
    proto = MockDiscoveryProtocol([])
    node = random_node()

    # Schedule a call to proto.recv_ping() simulating a ping from the node we expect.
    recv_ping_coroutine = asyncio.coroutine(lambda: proto.recv_ping_v4(node, echo, b""))
    asyncio.ensure_future(recv_ping_coroutine())

    got_ping = await proto.wait_ping(node)

    assert got_ping
    # Ensure wait_ping() cleaned up after itself.
    assert node not in proto.ping_callbacks

    # If we waited for a ping from a different node, wait_ping() would timeout and thus return
    # false.
    recv_ping_coroutine = asyncio.coroutine(lambda: proto.recv_ping_v4(node, echo, b""))
    asyncio.ensure_future(recv_ping_coroutine())

    node2 = random_node()
    got_ping = await proto.wait_ping(node2)

    assert not got_ping
    assert node2 not in proto.ping_callbacks 
开发者ID:QuarkChain,项目名称:pyquarkchain,代码行数:26,代码来源:test_discovery.py


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