Python uvloop.EventLoopPolicy() Examples

The following are 30 code examples of uvloop.EventLoopPolicy(). 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: __init__.py    From py-walletconnect-bridge with GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--redis-use-sentinel', action='store_true')
  parser.add_argument('--sentinels', type=str)
  parser.add_argument('--redis-host', type=str, default='localhost')
  parser.add_argument('--no-uvloop', action='store_true')
  parser.add_argument('--host', type=str, default='localhost')
  parser.add_argument('--port', type=int, default=8080)
  args = parser.parse_args()

  app = web.Application()
  app[REDIS] = {
    SENTINEL: args.redis_use_sentinel,
    SENTINELS: args.sentinels,
    HOST: args.redis_host
  }
  app.on_startup.append(initialize_client_session)
  app.on_startup.append(initialize_keystore)
  app.on_cleanup.append(close_keystore)
  app.on_cleanup.append(close_client_session_connection)
  app.router.add_routes(routes)
  if not args.no_uvloop:
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
  web.run_app(app, host=args.host, port=args.port) 
Example #2
Source File: simple_consume_bench.py    From aiokafka with Apache License 2.0 6 votes vote down vote up
def main():
    args = parse_args()
    if args.uvloop:
        import uvloop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

    loop = asyncio.get_event_loop()
    task = loop.create_task(Benchmark(args).bench_simple())
    task.add_done_callback(lambda _, loop=loop: loop.stop())

    def signal_hndl(_task=task):
        _task.cancel()
    loop.add_signal_handler(signal.SIGTERM, signal_hndl)
    loop.add_signal_handler(signal.SIGINT, signal_hndl)

    try:
        loop.run_forever()
    finally:
        loop.close()
        if not task.cancelled():
            task.result() 
Example #3
Source File: simple_produce_bench.py    From aiokafka with Apache License 2.0 6 votes vote down vote up
def main():
    args = parse_args()
    if args.uvloop:
        import uvloop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

    loop = asyncio.get_event_loop()
    task = loop.create_task(Benchmark(args).bench_simple())
    task.add_done_callback(lambda _, loop=loop: loop.stop())

    def signal_hndl(_task=task):
        _task.cancel()
    loop.add_signal_handler(signal.SIGTERM, signal_hndl)
    loop.add_signal_handler(signal.SIGINT, signal_hndl)

    try:
        loop.run_forever()
    finally:
        loop.close()
        if not task.cancelled():
            task.result() 
Example #4
Source File: __main__.py    From pydis with ISC License 6 votes vote down vote up
def main() -> int:
    print("Hello, World!")

    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

    loop = asyncio.get_event_loop()
    # Each client connection will create a new protocol instance
    coro = loop.create_server(RedisProtocol, "127.0.0.1", 7878)
    server = loop.run_until_complete(coro)

    # Serve requests until Ctrl+C is pressed
    print('Serving on {}'.format(server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    # Close the server
    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()

    return 0 
Example #5
Source File: cli.py    From aiodnsbrute with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, verbosity=0, max_tasks=512):
        """Constructor.

        Args:
            verbosity: set output verbosity: 0 (default) is none, 3 is debug
            max_tasks: the maximum number of tasks asyncio will queue (default 512)
        """
        self.tasks = []
        self.errors = []
        self.fqdn = []
        self.ignore_hosts = []
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
        self.loop = asyncio.get_event_loop()
        self.resolver = aiodns.DNSResolver(loop=self.loop, rotate=True)
        self.sem = asyncio.BoundedSemaphore(max_tasks)
        self.max_tasks = max_tasks
        self.verbosity = verbosity
        self.logger = ConsoleLogger(verbosity) 
Example #6
Source File: test_uvloop_integration.py    From aiologger with MIT License 6 votes vote down vote up
def test_it_logs_messages(self):
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
        loop = asyncio.get_event_loop()

        async def test():
            reader = asyncio.StreamReader(loop=loop)
            protocol = asyncio.StreamReaderProtocol(reader)

            transport, _ = await loop.connect_read_pipe(
                lambda: protocol, self.read_pipe
            )

            logger = Logger.with_default_handlers()
            await logger.info("Xablau")

            logged_content = await reader.readline()
            self.assertEqual(logged_content, b"Xablau\n")

            transport.close()
            await logger.shutdown()

        loop.run_until_complete(test()) 
Example #7
Source File: run.py    From hypercorn with MIT License 6 votes vote down vote up
def uvloop_worker(
    config: Config, sockets: Optional[Sockets] = None, shutdown_event: Optional[EventType] = None
) -> None:
    try:
        import uvloop
    except ImportError as error:
        raise Exception("uvloop is not installed") from error
    else:
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

    app = load_application(config.application_path)

    shutdown_trigger = None
    if shutdown_event is not None:
        shutdown_trigger = partial(check_multiprocess_shutdown_event, shutdown_event, asyncio.sleep)

    _run(
        partial(worker_serve, app, config, sockets=sockets),
        debug=config.debug,
        shutdown_trigger=shutdown_trigger,
    ) 
Example #8
Source File: simple_produce_bench.py    From aiokafka with Apache License 2.0 6 votes vote down vote up
def main():
    args = parse_args()
    if args.uvloop:
        import uvloop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

    loop = asyncio.get_event_loop()
    task = loop.create_task(Benchmark(args).bench_simple())
    task.add_done_callback(lambda _, loop=loop: loop.stop())

    def signal_hndl(_task=task):
        _task.cancel()
    loop.add_signal_handler(signal.SIGTERM, signal_hndl)
    loop.add_signal_handler(signal.SIGINT, signal_hndl)

    try:
        loop.run_forever()
    finally:
        loop.close()
        if not task.cancelled():
            task.result() 
Example #9
Source File: simple_consume_bench.py    From aiokafka with Apache License 2.0 6 votes vote down vote up
def main():
    args = parse_args()
    if args.uvloop:
        import uvloop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

    loop = asyncio.get_event_loop()
    task = loop.create_task(Benchmark(args).bench_simple())
    task.add_done_callback(lambda _, loop=loop: loop.stop())

    def signal_hndl(_task=task):
        _task.cancel()
    loop.add_signal_handler(signal.SIGTERM, signal_hndl)
    loop.add_signal_handler(signal.SIGINT, signal_hndl)

    try:
        loop.run_forever()
    finally:
        loop.close()
        if not task.cancelled():
            task.result() 
Example #10
Source File: worker.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def init_process(self):
        import tokio

        # Close any existing event loop before setting a
        # new policy.
        asyncio.get_event_loop().close()

        # Setup tokio policy, so that every
        # asyncio.get_event_loop() will create an instance
        # of tokio event loop.
        asyncio.set_event_loop_policy(tokio.EventLoopPolicy())

        super().init_process() 
Example #11
Source File: worker.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def init_process(self):
        import uvloop

        # Close any existing event loop before setting a
        # new policy.
        asyncio.get_event_loop().close()

        # Setup uvloop policy, so that every
        # asyncio.get_event_loop() will create an instance
        # of uvloop event loop.
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

        super().init_process() 
Example #12
Source File: tools.py    From owllook with Apache License 2.0 5 votes vote down vote up
def async_callback(func, **kwargs):
    """
    Call the asynchronous function
    :param func: a async function
    :param kwargs: params
    :return: result
    """
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    loop = asyncio.get_event_loop()
    task = asyncio.ensure_future(func(**kwargs))
    loop.run_until_complete(task)
    return task.result() 
Example #13
Source File: novels_schedule.py    From owllook with Apache License 2.0 5 votes vote down vote up
def update_all():
    # asyncio.get_event_loop().run_until_complete(update_all_books())
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    loop = asyncio.get_event_loop()
    task = asyncio.ensure_future(update_all_books(loop=loop, timeout=15))
    loop.run_until_complete(task)
    return task.result() or None 
Example #14
Source File: __init__.py    From asyncpg with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        if os.environ.get('USE_UVLOOP'):
            import uvloop
            asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)
        cls.loop = loop 
Example #15
Source File: worker.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def init_process(self):
        import uvloop

        # Close any existing event loop before setting a
        # new policy.
        asyncio.get_event_loop().close()

        # Setup uvloop policy, so that every
        # asyncio.get_event_loop() will create an instance
        # of uvloop event loop.
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

        super().init_process() 
Example #16
Source File: worker.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def init_process(self):
        import tokio

        # Close any existing event loop before setting a
        # new policy.
        asyncio.get_event_loop().close()

        # Setup tokio policy, so that every
        # asyncio.get_event_loop() will create an instance
        # of tokio event loop.
        asyncio.set_event_loop_policy(tokio.EventLoopPolicy())

        super().init_process() 
Example #17
Source File: conftest.py    From threema-msgapi-sdk-python with MIT License 5 votes vote down vote up
def default_event_loop(request=None, config=None):
    if request is not None:
        config = request.config
    loop = config.getoption("--loop")
    if loop == 'uvloop':
        import uvloop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    else:
        loop = 'asyncio'
    return loop 
Example #18
Source File: conftest.py    From aiotask-context with MIT License 5 votes vote down vote up
def uvloop_loop():
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    loop = asyncio.get_event_loop()
    yield loop
    loop.close()
    # restore the virgin state
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) 
Example #19
Source File: utils.py    From postfix-mta-sts-resolver with MIT License 5 votes vote down vote up
def enable_uvloop():  # pragma: no cover
    try:
        # pylint: disable=import-outside-toplevel
        import uvloop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    except ImportError:
        return False
    else:
        return True 
Example #20
Source File: scripts.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def init_asyncio_reactor():
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    try:
        asyncioreactor.install()
    except error.ReactorAlreadyInstalledError:
        pass 
Example #21
Source File: conftest.py    From aiosmtplib with MIT License 5 votes vote down vote up
def event_loop_policy(request):
    loop_type = request.config.getoption("--event-loop")
    if loop_type == "uvloop":
        if not HAS_UVLOOP:
            raise RuntimeError("uvloop not installed.")
        old_policy = asyncio.get_event_loop_policy()
        policy = uvloop.EventLoopPolicy()
        asyncio.set_event_loop_policy(policy)
        request.addfinalizer(lambda: asyncio.set_event_loop_policy(old_policy))

    return asyncio.get_event_loop_policy() 
Example #22
Source File: env.py    From lbry-sdk with MIT License 5 votes vote down vote up
def set_event_loop_policy(self):
        policy_name = self.default('EVENT_LOOP_POLICY', None)
        if not policy_name:
            import asyncio
            return asyncio.get_event_loop_policy()
        elif policy_name == 'uvloop':
            import uvloop
            import asyncio
            loop_policy = uvloop.EventLoopPolicy()
            asyncio.set_event_loop_policy(loop_policy)
            return loop_policy
        raise self.Error(f'unknown event loop policy "{policy_name}"') 
Example #23
Source File: request.py    From OneForAll with GNU General Public License v3.0 5 votes vote down vote up
def set_loop_policy():
    try:
        import uvloop
    except ImportError:
        pass
    else:
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) 
Example #24
Source File: conftest.py    From aioredis with MIT License 5 votes vote down vote up
def pytest_configure(config):
    bins = config.getoption('--redis-server')[:]
    cmd = 'which redis-server'
    if not bins:
        with os.popen(cmd) as pipe:
            path = pipe.read().rstrip()
        assert path, (
            "There is no redis-server on your computer."
            " Please install it first")
        REDIS_SERVERS[:] = [path]
    else:
        REDIS_SERVERS[:] = bins

    VERSIONS.update({srv: _read_server_version(srv)
                     for srv in REDIS_SERVERS})
    assert VERSIONS, ("Expected to detect redis versions", REDIS_SERVERS)

    class DynamicFixturePlugin:
        @pytest.fixture(scope='session',
                        params=REDIS_SERVERS,
                        ids=format_version)
        def server_bin(self, request):
            """Common for start_server and start_sentinel
            server bin path parameter.
            """
            return request.param
    config.pluginmanager.register(DynamicFixturePlugin(), 'server-bin-fixture')

    if config.getoption('--uvloop'):
        try:
            import uvloop
        except ImportError:
            raise RuntimeError(
                "Can not import uvloop, make sure it is installed")
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) 
Example #25
Source File: mtprotoproxy.py    From mtprotoproxy with MIT License 5 votes vote down vote up
def try_setup_uvloop():
    if config.SOCKS5_HOST and config.SOCKS5_PORT:
        # socks mode is not compatible with uvloop
        return
    try:
        import uvloop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
        print_err("Found uvloop, using it for optimal performance")
    except ImportError:
        pass 
Example #26
Source File: worker.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def run_worker(cls, cls_args, sockname):
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    with devmode.CoverageConfig.enable_coverage_if_requested():
        asyncio.run(worker(cls, cls_args, sockname)) 
Example #27
Source File: env.py    From torba with MIT License 5 votes vote down vote up
def event_loop_policy(self):
        policy = self.default('EVENT_LOOP_POLICY', None)
        if policy is None:
            return None
        if policy == 'uvloop':
            import uvloop
            return uvloop.EventLoopPolicy()
        raise self.Error('unknown event loop policy "{}"'.format(policy)) 
Example #28
Source File: conftest.py    From saltyrtc-server-python with MIT License 5 votes vote down vote up
def default_event_loop(request=None, config=None):
    if request is not None:
        config = request.config
    loop = config.getoption("--loop")
    if loop == 'uvloop':
        import uvloop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    else:
        loop = 'asyncio'
    return loop 
Example #29
Source File: pytest_plugin.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def pytest_generate_tests(metafunc):  # type: ignore
    if 'loop_factory' not in metafunc.fixturenames:
        return

    loops = metafunc.config.option.aiohttp_loop
    avail_factories = {'pyloop': asyncio.DefaultEventLoopPolicy}

    if uvloop is not None:  # pragma: no cover
        avail_factories['uvloop'] = uvloop.EventLoopPolicy

    if tokio is not None:  # pragma: no cover
        avail_factories['tokio'] = tokio.EventLoopPolicy

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

    factories = {}  # type: ignore
    for name in loops.split(','):
        required = not name.endswith('?')
        name = name.strip(' ?')
        if name not in avail_factories:  # pragma: no cover
            if required:
                raise ValueError(
                    "Unknown loop '%s', available loops: %s" % (
                        name, list(factories.keys())))
            else:
                continue
        factories[name] = avail_factories[name]
    metafunc.parametrize("loop_factory",
                         list(factories.values()),
                         ids=list(factories.keys())) 
Example #30
Source File: utils.py    From rsp with MIT License 5 votes vote down vote up
def enable_uvloop():  # pragma: no cover
    try:
        import uvloop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    except ImportError:
        return False
    else:
        return True