Python uvloop.new_event_loop() Examples

The following are 29 code examples of uvloop.new_event_loop(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module uvloop , or try the search function .
Example #1
Source File: run.py    From falsy with MIT License 6 votes vote down vote up
def run(coro, loop=None):
    async def main_task():
        pycurl_task = aio.ensure_future(curl_loop())
        try:
            r = await coro
        finally:
            pycurl_task.cancel()
            with suppress(aio.CancelledError):
                await pycurl_task
        return r, pycurl_task

    if loop is None:
        loop = uvloop.new_event_loop()
        # loop = aio.get_event_loop()
    aio.set_event_loop(loop)
    loop.set_exception_handler(exception_handler)
    r, _ = loop.run_until_complete(main_task())
    return r 
Example #2
Source File: conftest.py    From aiomysql with MIT License 6 votes vote down vote up
def loop(request, loop_type):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(None)

    if uvloop and loop_type == 'uvloop':
        loop = uvloop.new_event_loop()
    else:
        loop = asyncio.new_event_loop()

    yield loop

    if not loop._closed:
        loop.call_soon(loop.stop)
        loop.run_forever()
        loop.close()
    gc.collect()
    asyncio.set_event_loop(None) 
Example #3
Source File: plugin.py    From pytest-sanic with Apache License 2.0 6 votes vote down vote up
def pytest_configure(config):
    global LOOP_INIT
    loop_name = config.getoption('--loop')
    factory = {
        "aioloop": asyncio.new_event_loop,
    }
    if uvloop is not None:
        factory["uvloop"] = uvloop.new_event_loop

    if loop_name:
        if loop_name not in factory:
            raise ValueError(
                "{name} is not valid option".format(name=loop_name)
            )
        LOOP_INIT = factory[loop_name]
    else:
        LOOP_INIT = factory["aioloop"] 
Example #4
Source File: conftest.py    From aiomonitor with Apache License 2.0 5 votes vote down vote up
def loop(request, loop_type):
    old_loop = asyncio.get_event_loop()
    asyncio.set_event_loop(None)
    if loop_type == 'uvloop':
        loop = uvloop.new_event_loop()
    else:
        loop = asyncio.new_event_loop()

    yield loop

    loop.close()
    asyncio.set_event_loop(old_loop)
    gc.collect() 
Example #5
Source File: manage.py    From rasa_wechat with Apache License 2.0 5 votes vote down vote up
def run():
    asyncio.set_event_loop(uvloop.new_event_loop())
    server = app.create_server(host="0.0.0.0", port=80)
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(server)
    signal(SIGINT, lambda s, f: loop.stop())
    try:
        loop.run_forever()
    except:
        loop.stop() 
Example #6
Source File: pytest_plugin.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def pytest_configure(config):
    loops = config.getoption('--loop')

    factories = {'pyloop': asyncio.new_event_loop}

    if uvloop is not None:  # pragma: no cover
        factories['uvloop'] = uvloop.new_event_loop

    if tokio is not None:  # pragma: no cover
        factories['tokio'] = tokio.new_event_loop

    LOOP_FACTORIES.clear()
    LOOP_FACTORY_IDS.clear()

    if loops:
        for names in (name.split(',') for name in loops):
            for name in names:
                name = name.strip()
                if name not in factories:
                    raise ValueError(
                        "Unknown loop '%s', available loops: %s" % (
                            name, list(factories.keys())))

                LOOP_FACTORIES.append(factories[name])
                LOOP_FACTORY_IDS.append(name)
    else:
        LOOP_FACTORIES.append(asyncio.new_event_loop)
        LOOP_FACTORY_IDS.append('pyloop')

        if uvloop is not None:  # pragma: no cover
            LOOP_FACTORIES.append(uvloop.new_event_loop)
            LOOP_FACTORY_IDS.append('uvloop')

        if tokio is not None:
            LOOP_FACTORIES.append(tokio.new_event_loop)
            LOOP_FACTORY_IDS.append('tokio')

    asyncio.set_event_loop(None) 
Example #7
Source File: pytest_plugin.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def pytest_configure(config):
    loops = config.getoption('--loop')

    factories = {'pyloop': asyncio.new_event_loop}

    if uvloop is not None:  # pragma: no cover
        factories['uvloop'] = uvloop.new_event_loop

    if tokio is not None:  # pragma: no cover
        factories['tokio'] = tokio.new_event_loop

    LOOP_FACTORIES.clear()
    LOOP_FACTORY_IDS.clear()

    if loops:
        for names in (name.split(',') for name in loops):
            for name in names:
                name = name.strip()
                if name not in factories:
                    raise ValueError(
                        "Unknown loop '%s', available loops: %s" % (
                            name, list(factories.keys())))

                LOOP_FACTORIES.append(factories[name])
                LOOP_FACTORY_IDS.append(name)
    else:
        LOOP_FACTORIES.append(asyncio.new_event_loop)
        LOOP_FACTORY_IDS.append('pyloop')

        if uvloop is not None:  # pragma: no cover
            LOOP_FACTORIES.append(uvloop.new_event_loop)
            LOOP_FACTORY_IDS.append('uvloop')

        if tokio is not None:
            LOOP_FACTORIES.append(tokio.new_event_loop)
            LOOP_FACTORY_IDS.append('tokio')

    asyncio.set_event_loop(None) 
Example #8
Source File: conftest.py    From aiorwlock with Apache License 2.0 5 votes vote down vote up
def event_loop(request, loop_type, debug):
    # old_loop = asyncio.get_event_loop()
    asyncio.set_event_loop(None)
    if loop_type == 'uvloop':
        loop = uvloop.new_event_loop()
    else:
        loop = asyncio.new_event_loop()

    loop.set_debug(debug)
    asyncio.set_event_loop(loop)
    yield loop

    loop.close()
    asyncio.set_event_loop(None)
    gc.collect() 
Example #9
Source File: pytest_plugin.py    From aiosip with Apache License 2.0 5 votes vote down vote up
def loop_context(loop_factory=asyncio.new_event_loop, fast=False):
    """A contextmanager that creates an event_loop, for test purposes.

    Handles the creation and cleanup of a test loop.
    """
    loop = setup_test_loop(loop_factory)
    yield loop
    teardown_test_loop(loop, fast=fast) 
Example #10
Source File: bottle.py    From slack-machine with MIT License 5 votes vote down vote up
def get_event_loop(self):
        import uvloop
        return uvloop.new_event_loop() 
Example #11
Source File: bottle.py    From slack-machine with MIT License 5 votes vote down vote up
def get_event_loop(self):
        import asyncio
        return asyncio.new_event_loop() 
Example #12
Source File: benchmark_aiorpc_inet.py    From aiorpc with Do What The F*ck You Want To Public License 5 votes vote down vote up
def call():
    async def do(cli):
        for i in range(NUM_CALLS):
            await cli.call('sum', 1, 2)
            # print('{} call'.format(i))
    client = aiorpc.RPCClient('localhost', 6000)
    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
    start = time.time()

    loop.run_until_complete(do(client))

    print('call: %d qps' % (NUM_CALLS / (time.time() - start))) 
Example #13
Source File: benchmark_aiorpc_inet.py    From aiorpc with Do What The F*ck You Want To Public License 5 votes vote down vote up
def run_sum_server():
    def sum(x, y):
        return x + y

    aiorpc.register('sum', sum)
    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
    coro = asyncio.start_server(aiorpc.serve, 'localhost', 6000, loop=loop)
    loop.run_until_complete(coro)
    loop.run_forever() 
Example #14
Source File: benchmark_aiorpc_unix.py    From aiorpc with Do What The F*ck You Want To Public License 5 votes vote down vote up
def call():
    async def do(cli):
        for i in range(NUM_CALLS):
            await cli.call('sum', 1, 2)
            # print('{} call'.format(i))
    client = aiorpc.RPCClient(path='./benchmark.socket')
    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
    start = time.time()

    loop.run_until_complete(do(client))

    print('call: %d qps' % (NUM_CALLS / (time.time() - start))) 
Example #15
Source File: benchmark_aiorpc_unix.py    From aiorpc with Do What The F*ck You Want To Public License 5 votes vote down vote up
def run_sum_server():
    def sum(x, y):
        return x + y

    aiorpc.register('sum', sum)
    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
    coro = asyncio.start_unix_server(aiorpc.serve, './benchmark.socket', loop=loop)
    loop.run_until_complete(coro)
    loop.run_forever() 
Example #16
Source File: async_compat.py    From ray with Apache License 2.0 5 votes vote down vote up
def get_new_event_loop():
    """Construct a new event loop. Ray will use uvloop if it exists"""
    if uvloop:
        return uvloop.new_event_loop()
    else:
        return asyncio.new_event_loop() 
Example #17
Source File: pytest_plugin.py    From aiosip with Apache License 2.0 5 votes vote down vote up
def setup_test_loop(loop_factory=asyncio.new_event_loop):
    """Create and return an asyncio.BaseEventLoop instance.

    The caller should also call teardown_test_loop, once they are done
    with the loop.
    """
    loop = loop_factory()
    asyncio.set_event_loop(loop)
    if sys.platform != "win32":
        policy = asyncio.get_event_loop_policy()
        watcher = asyncio.SafeChildWatcher()
        watcher.attach_loop(loop)
        policy.set_child_watcher(watcher)
    return loop 
Example #18
Source File: manage.py    From momo with Apache License 2.0 5 votes vote down vote up
def run():
    asyncio.set_event_loop(uvloop.new_event_loop())
    server = app.create_server(host="0.0.0.0", port=8888)
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(server)
    signal(SIGINT, lambda s, f: loop.stop())
    try:
        loop.run_forever()
    except:
        loop.stop() 
Example #19
Source File: base.py    From butian-src-domains with GNU General Public License v3.0 5 votes vote down vote up
def event_loop(self):
        q = asyncio.Queue()
        for request_item in self.request_list:
            q.put_nowait(request_item)
        loop = uvloop.new_event_loop()
        asyncio.set_event_loop(loop)
        tasks = [self.handle_tasks(task_id, q) for task_id in range(self.coroutine_num)]
        loop.run_until_complete(asyncio.wait(tasks))
        loop.close() 
Example #20
Source File: aioscript.py    From aioscript with MIT License 5 votes vote down vote up
def _setup_loop(self, use_uvloop):
        debug = bool(os.environ.get('PYTHONASYNCIODEBUG'))

        if use_uvloop:
            import uvloop
            loop = uvloop.new_event_loop()
        else:
            import asyncio
            loop = asyncio.new_event_loop()

        loop.set_debug(debug)

        return loop 
Example #21
Source File: loop.py    From switchio with Mozilla Public License 2.0 5 votes vote down vote up
def _run_loop(self, debug):
        self.loop = loop = new_event_loop()
        loop._tid = get_ident()
        # FIXME: causes error with a thread safety check in Future.call_soon()
        # called from Future.add_done_callback() - stdlib needs a patch?
        if debug:
            loop.set_debug(debug)
            logging.getLogger('asyncio').setLevel(logging.DEBUG)
        asyncio.set_event_loop(loop)
        self.loop.run_forever() 
Example #22
Source File: loop.py    From switchio with Mozilla Public License 2.0 5 votes vote down vote up
def new_event_loop():
    """Get the fastest loop available.
    """
    try:
        import uvloop
        return uvloop.new_event_loop()
    except ImportError as err:
        utils.log_to_stderr().warn(str(err))
        return asyncio.new_event_loop() 
Example #23
Source File: manager.py    From Metis with Apache License 2.0 5 votes vote down vote up
def run():
    asyncio.set_event_loop(uvloop.new_event_loop())
    server = app.create_server(host="0.0.0.0", port=7777)
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(server)
    signal(SIGINT, lambda s, f: loop.stop())
    try:
        loop.run_forever()
    except:
        loop.stop() 
Example #24
Source File: bottle.py    From silvia-pi with MIT License 5 votes vote down vote up
def get_event_loop(self):
        import uvloop
        return uvloop.new_event_loop() 
Example #25
Source File: bottle.py    From silvia-pi with MIT License 5 votes vote down vote up
def get_event_loop(self):
        import asyncio
        return asyncio.new_event_loop() 
Example #26
Source File: publisher.py    From pydata2019-nlp-system with Apache License 2.0 5 votes vote down vote up
def publish(self, channel_name='processed'):
        signal(SIGINT, interrupt_handler)
        try:
            loop = uvloop.new_event_loop()
            bot = Bot(token=getenv('TELEGRAM_KEY'), loop=loop)
            task = loop.create_task(subscribe_and_listen(bot, channel_name))
            loop.run_until_complete(task)
        finally:
            task.cancel()
            loop.run_until_complete(bot.close())
            loop.close() 
Example #27
Source File: pubsub_redis.py    From pydata2019-nlp-system with Apache License 2.0 5 votes vote down vote up
def launch_pubsub_task(func: Callable, 
        source='comments', sink='processed', subprocess=False):
    async def pubsub_func():
        r = redis.Redis(REDIS_HOST)
        async for message in listen(source):
            if message is StopAsyncIteration:
                break
            output = func(message['data'])
            if output is not None:
                await publish(r, sink, output)

    def run_task():
        loop = uvloop.new_event_loop()
        task = loop.create_task(pubsub_func())    
        try:
            loop.run_until_complete(task)
        finally:
            print('Stopping...')
            task.cancel()
            loop.stop()
            loop.close()

    signal(SIGINT, interrupt_handler)

    if subprocess:
        process = Process(target=run_task)
        process.start()
    else:
        run_task() 
Example #28
Source File: publisher.py    From pydata2019-nlp-system with Apache License 2.0 5 votes vote down vote up
def publish(self, channel_name='ready'):
        signal(SIGINT, interrupt_handler)
        try:
            loop = uvloop.new_event_loop()
            bot = Bot(token=getenv('TELEGRAM_KEY'), loop=loop)
            task = loop.create_task(subscribe_and_listen(bot, channel_name))
            loop.run_until_complete(task)
        finally:
            task.cancel()
            loop.run_until_complete(bot.close())
            loop.close() 
Example #29
Source File: pytest_plugin.py    From aiosip with Apache License 2.0 5 votes vote down vote up
def pytest_configure(config):
    loops = config.getoption('--loop')

    factories = {'pyloop': asyncio.new_event_loop}

    if uvloop is not None:  # pragma: no cover
        factories['uvloop'] = uvloop.new_event_loop

    if tokio is not None:  # pragma: no cover
        factories['tokio'] = tokio.new_event_loop

    LOOP_FACTORIES.clear()
    LOOP_FACTORY_IDS.clear()

    if loops == 'all':
        loops = 'pyloop,uvloop?,tokio?'

    for name in loops.split(','):
        required = not name.endswith('?')
        name = name.strip(' ?')
        if name in factories:
            LOOP_FACTORIES.append(factories[name])
            LOOP_FACTORY_IDS.append(name)
        elif required:
            raise ValueError(
                "Unknown loop '%s', available loops: %s" % (
                    name, list(factories.keys())))
    asyncio.set_event_loop(None)