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


Python asyncio.new_event_loop方法代码示例

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


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

示例1: listen_message_stream

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def listen_message_stream(self, id_blacklist=None):
        id_blacklist = set(id_blacklist or [self.me, ])

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        with aiohttp.ClientSession(loop=loop) as session:
            self.aioclient_session = session

            tasks = [
                asyncio.ensure_future(self.fetch(session, room, id_blacklist))
                for room in self.rooms
            ]
            done, _ = loop.run_until_complete(
                asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
            )
            for d in done:
                if d.exception():
                    raise d.exception() 
开发者ID:tuna,项目名称:fishroom,代码行数:20,代码来源:gitter.py

示例2: test_logo_base

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def test_logo_base(app, caplog):
    server = app.create_server(
        debug=True, return_asyncio_server=True, port=PORT
    )
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop._stopping = False

    with caplog.at_level(logging.DEBUG):
        _server = loop.run_until_complete(server)

    _server.close()
    loop.run_until_complete(_server.wait_closed())
    app.stop()

    assert caplog.record_tuples[ROW][1] == logging.DEBUG
    assert caplog.record_tuples[ROW][2] == BASE_LOGO 
开发者ID:huge-success,项目名称:sanic,代码行数:19,代码来源:test_logo.py

示例3: test_logo_false

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def test_logo_false(app, caplog):
    app.config.LOGO = False

    server = app.create_server(
        debug=True, return_asyncio_server=True, port=PORT
    )
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop._stopping = False

    with caplog.at_level(logging.DEBUG):
        _server = loop.run_until_complete(server)

    _server.close()
    loop.run_until_complete(_server.wait_closed())
    app.stop()

    banner, port = caplog.record_tuples[ROW][2].rsplit(":", 1)
    assert caplog.record_tuples[ROW][1] == logging.INFO
    assert banner == "Goin' Fast @ http://127.0.0.1"
    assert int(port) > 0 
开发者ID:huge-success,项目名称:sanic,代码行数:23,代码来源:test_logo.py

示例4: test_logo_custom

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def test_logo_custom(app, caplog):
    app.config.LOGO = "My Custom Logo"

    server = app.create_server(
        debug=True, return_asyncio_server=True, port=PORT
    )
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop._stopping = False

    with caplog.at_level(logging.DEBUG):
        _server = loop.run_until_complete(server)

    _server.close()
    loop.run_until_complete(_server.wait_closed())
    app.stop()

    assert caplog.record_tuples[ROW][1] == logging.DEBUG
    assert caplog.record_tuples[ROW][2] == "My Custom Logo" 
开发者ID:huge-success,项目名称:sanic,代码行数:21,代码来源:test_logo.py

示例5: test_keep_alive_timeout_reuse

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def test_keep_alive_timeout_reuse():
    """If the server keep-alive timeout and client keep-alive timeout are
     both longer than the delay, the client _and_ server will successfully
     reuse the existing connection."""
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        client = ReuseableSanicTestClient(keep_alive_timeout_app_reuse, loop)
        headers = {"Connection": "keep-alive"}
        request, response = client.get("/1", headers=headers)
        assert response.status == 200
        assert response.text == "OK"
        loop.run_until_complete(aio_sleep(1))
        request, response = client.get("/1")
        assert response.status == 200
        assert response.text == "OK"
    finally:
        client.kill_server() 
开发者ID:huge-success,项目名称:sanic,代码行数:20,代码来源:test_keep_alive_timeout.py

示例6: test_keep_alive_client_timeout

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def test_keep_alive_client_timeout():
    """If the server keep-alive timeout is longer than the client
    keep-alive timeout, client will try to create a new connection here."""
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        client = ReuseableSanicTestClient(keep_alive_app_client_timeout, loop)
        headers = {"Connection": "keep-alive"}
        try:
            request, response = client.get(
                "/1", headers=headers, request_keepalive=1
            )
            assert response.status == 200
            assert response.text == "OK"
            loop.run_until_complete(aio_sleep(2))
            exception = None
            request, response = client.get("/1", request_keepalive=1)
        except ValueError as e:
            exception = e
        assert exception is not None
        assert isinstance(exception, ValueError)
        assert "got a new connection" in exception.args[0]
    finally:
        client.kill_server() 
开发者ID:huge-success,项目名称:sanic,代码行数:26,代码来源:test_keep_alive_timeout.py

示例7: loop

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def loop():
    """Creates new event loop."""
    loop = asyncio.new_event_loop()
    if sys.version_info < (3, 8):
        asyncio.set_event_loop(loop)

    try:
        yield loop
    finally:
        if hasattr(loop, 'is_closed'):
            closed = loop.is_closed()
        else:
            closed = loop._closed   # XXX
        if not closed:
            loop.call_soon(loop.stop)
            loop.run_forever()
            loop.close() 
开发者ID:aio-libs,项目名称:aioredis,代码行数:19,代码来源:conftest.py

示例8: _run_in_fresh_loop

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def _run_in_fresh_loop(coro, timeout=30):
    thres = []
    thexc = []

    def run():
        loop = asyncio.new_event_loop()
        try:
            task = loop.create_task(coro(loop=loop))
            thres.append(loop.run_until_complete(task))
        except Exception as e:
            thexc.append(e)
        finally:
            loop.close()

    th = threading.Thread(target=run)
    th.start()
    th.join(timeout=timeout)

    # re-raise a thread exception
    if len(thexc) > 0:
        raise thexc[0]

    return thres[0] 
开发者ID:loads,项目名称:molotov,代码行数:25,代码来源:util.py

示例9: run_worker

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def run_worker(input):
    if os.getpid() not in _PROC:
        _PROC.append(os.getpid())
    _CONSOLE.print("hello")
    try:
        3 + ""
    except Exception:
        _CONSOLE.print_error("meh")

    with catch_output() as (stdout, stderr):
        loop = asyncio.new_event_loop()
        fut = asyncio.ensure_future(_CONSOLE.display(), loop=loop)
        loop.run_until_complete(fut)
        loop.close()

    stdout = stdout.read()
    assert stdout == "", stdout 
开发者ID:loads,项目名称:molotov,代码行数:19,代码来源:test_sharedconsole.py

示例10: async_test

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [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

示例11: ad_hoc

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def ad_hoc() -> None:
    try:
        event_loop = asyncio.get_event_loop()
    except RuntimeError:
        event_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(event_loop)

    league.set_status(league.Status.CLOSED)
    multiverse.init() # New Cards?
    event_loop.run_until_complete(multiverse.set_legal_cards_async()) # PD current list
    event_loop.run_until_complete(multiverse.update_pd_legality_async()) # PD previous lists
    insert_seasons.run() # Make sure Season table is up to date
    if redis.REDIS: # Clear the redis cache
        redis.REDIS.flushdb()
    league_end = league.active_league().end_date
    diff = league_end - dtutil.now()
    if diff.days > 0:
        league.set_status(league.Status.OPEN)
    print('Open the gates here')
    reprime_cache.run() # Update deck legalities
    if redis.REDIS: # Clear the redis cache
        redis.REDIS.flushdb() 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:24,代码来源:post_rotation.py

示例12: setUp

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def setUp(self):
        setup_mock_web_api_server(self)

        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        task = asyncio.ensure_future(self.mock_server(), loop=self.loop)
        self.loop.run_until_complete(asyncio.wait_for(task, 0.1))

        self.client = slack.RTMClient(
            token="xoxb-valid",
            base_url="http://localhost:8765",
            auto_reconnect=False,
            run_async=False,
        )
        self.client._web_client = slack.WebClient(
            token="xoxb-valid",
            base_url="http://localhost:8888",
            run_async=False,
        ) 
开发者ID:slackapi,项目名称:python-slackclient,代码行数:21,代码来源:test_rtm_client_functional.py

示例13: test_the_cost_of_event_loop_creation

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def test_the_cost_of_event_loop_creation(self):
        # create 100 event loops
        loops = []
        try:
            upper_limit = 0
            for i in range(1000):
                try:
                    loops.append(asyncio.new_event_loop())
                except OSError as e:
                    self.logger.info(f"Got an OSError when creating {i} event loops")
                    self.assertEqual(e.errno, 24)
                    self.assertEqual(e.strerror, "Too many open files")
                    upper_limit = i
                    break
            self.assertTrue(upper_limit > 0)
        finally:
            for loop in loops:
                loop.close() 
开发者ID:slackapi,项目名称:python-slackclient,代码行数:20,代码来源:test_asyncio_event_loops.py

示例14: per_request_async

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def per_request_async():
    try:
        # This is not optimal and the host should have a large number of FD (File Descriptor)
        loop_for_this_request = asyncio.new_event_loop()

        async_client = WebClient(
            token=os.environ["SLACK_BOT_TOKEN"],
            run_async=True,
            loop=loop_for_this_request
        )
        future = async_client.chat_postMessage(
            channel="#random",
            text="You used the singleton WebClient for posting this message!"
        )
        response = loop_for_this_request.run_until_complete(future)
        return str(response)
    except SlackApiError as e:
        return make_response(str(e), 400) 
开发者ID:slackapi,项目名称:python-slackclient,代码行数:20,代码来源:issue_497.py

示例15: handle

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import new_event_loop [as 别名]
def handle(self, *args, **kwargs):
        """Run the executor listener. This method never returns."""
        listener = ExecutorListener(
            redis_params=getattr(settings, "FLOW_MANAGER", {}).get(
                "REDIS_CONNECTION", {}
            )
        )

        def _killer(signum, frame):
            """Kill the listener on receipt of a signal."""
            listener.terminate()

        signal(SIGINT, _killer)
        signal(SIGTERM, _killer)

        async def _runner():
            """Run the listener instance."""
            if kwargs["clear_queue"]:
                await listener.clear_queue()
            async with listener:
                pass

        loop = asyncio.new_event_loop()
        loop.run_until_complete(_runner())
        loop.close() 
开发者ID:genialis,项目名称:resolwe,代码行数:27,代码来源:runlistener.py


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