Example #1
0
def load_and_run_tshell():
    """Launch a shell for a thrift service."""
    parser = argparse.ArgumentParser(
        description=
        "Open a shell for a Thrift service with app configuration loaded.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument("--debug",
                        action="store_true",
                        default=False,
                        help="enable extra-verbose debug logging")
    parser.add_argument(
        "--app-name",
        default="main",
        metavar="NAME",
        help="name of app to load from config_file (default: main)")
    parser.add_argument("config_file",
                        type=argparse.FileType("r"),
                        help="path to a configuration file")

    args = parser.parse_args(sys.argv[1:])
    config = read_config(args.config_file,
                         server_name=None,
                         app_name=args.app_name)
    logging.basicConfig(level=logging.INFO)

    env = dict()
    env_banner = {
        'app': "This project's app instance",
        'context': "The context for this shell instance's span",
    }

    app = make_app(config.app)
    env['app'] = app

    span = app.baseplate.make_server_span(RequestContext(), 'shell')
    env['context'] = span.context

    if config.tshell and 'setup' in config.tshell:
        setup = _load_factory(config.tshell['setup'])
        setup(env, env_banner)

    # generate banner text
    banner = "Available Objects:\n"
    for var in sorted(env_banner.keys()):
        banner += '\n  %-12s %s' % (var, env_banner[var])

    try:
        # try to use IPython if possible
        from IPython.terminal.embed import InteractiveShellEmbed
        shell = InteractiveShellEmbed(banner2=banner)
        shell(local_ns=env, global_ns={})
    except ImportError:
        import code
        newbanner = "Baseplate Interactive Shell\nPython {}\n\n".format(
            sys.version)
        banner = newbanner + banner
        shell = code.InteractiveConsole(locals=env)
        shell.interact(banner)
Example #2
0
def attach():
    """
    Enter a python shell with contracts and blockchain client
    available.
    """
    project_dir = os.path.abspath(os.getcwd())
    contracts_meta = utils.load_contracts(project_dir)

    context = {
        'contracts': package_contracts(contracts_meta),
        'client': Client('127.0.0.1', '8545'),
    }

    contract_names = ', '.join(sorted(contracts_meta.keys()))

    banner = textwrap.dedent(
        """
        Python: {python_version}

        Populus: v{populus_version}

        Project Path: {project_dir}

        contracts  -> Contract classes
        client     -> Blockchain client ({client_type})

        Contracts: {contracts}
        """
    ).format(
        python_version=sys.version.partition('\n')[0],
        populus_version=populus.__version__,
        project_dir=project_dir,
        client_type="json-rpc",
        contracts=click.wrap_text(
            contract_names, initial_indent='', subsequent_indent=' ' * 4,
        ),
    ).strip()

    if is_ipython:
        shell = InteractiveConsole(user_ns=context)
    else:
        shell = InteractiveConsole(context)
    shell.interact(banner)
Example #3
0
def attach(active):
    """
    Enter a python shell with contracts and blockchain client
    available.
    """
    project_dir = os.path.abspath(os.getcwd())
    contracts_meta = utils.load_contracts(project_dir)
    client = Client('127.0.0.1', '8545')

    context = {
        'contracts': package_contracts(contracts_meta),
        'client': client,
    }
    data_dir = None
    if active:
        data_dir = get_active_data_dir(project_dir)
        if os.path.islink(data_dir):
            setup_known_instances(context, data_dir)
        else:
            click.echo(click.style("No Valid Active Chain Data Directory Found!", fg="red"))

    def redeploy(contracts=[], record=True):
        return(deploy_set(
            context, client, project_dir, data_dir=data_dir,
            record=record, contracts_by_name=contracts
        ))

    context["redeploy"] = redeploy

    contract_names = ', '.join(sorted(contracts_meta.keys()))

    banner = textwrap.dedent(
        """
        Python: {python_version}

        Populus: v{populus_version}

        Project Path: {project_dir}

        contracts  -> Contract classes
        client     -> Blockchain client ({client_type})
        redeploy   -> Method to re-deploy project contracts
                      Example:
                        deployed_cts = redeploy()
                        deployed_cts = redeploy(record = False)
                        deployed_cts = redeploy(contracts = ["Example"])

        Contracts: {contracts}
        Check contracts.<type>.known for deployed contracts.

        """
    ).format(
        python_version=sys.version.partition('\n')[0],
        populus_version=populus.__version__,
        project_dir=project_dir,
        client_type="json-rpc",
        contracts=click.wrap_text(
            contract_names, initial_indent='', subsequent_indent=' ' * 4,
        ),
    ).strip()

    if is_ipython:
        shell = InteractiveConsole(user_ns=context)
    else:
        shell = InteractiveConsole(context)

    # Start the active directory link observer
    event_handler = ActiveDataDirChangedEventHandler(
        project_dir=project_dir,
        context=context,
    )
    observer = get_active_dir_observer(project_dir, event_handler)

    observer.start()
    shell.interact(banner)
    observer.stop()
    observer.join()
Example #4
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        # Determine the package name from the pylons.config object
        pkg_name = pylons.config['pylons.package']

        # Start the rest of our imports now that the app is loaded
        if is_minimal_template(pkg_name, True):
            model_module = None
            helpers_module = pkg_name + '.helpers'
            base_module = pkg_name + '.controllers'
        else:
            model_module = pkg_name + '.model'
            helpers_module = pkg_name + '.lib.helpers'
            base_module = pkg_name + '.lib.base'

        if model_module and can_import(model_module):
            locs['model'] = sys.modules[model_module]

        if can_import(helpers_module):
            locs['h'] = sys.modules[helpers_module]

        exec ('from pylons import app_globals, config, request, response, '
              'session, tmpl_context, url') in locs
        exec ('from pylons.controllers.util import abort, redirect') in locs
        exec 'from pylons.i18n import _, ungettext, N_' in locs
        locs.pop('__builtins__', None)

        # Import all objects from the base module
        __import__(base_module)

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not \
                       __name.startswith('_') or __name == '_']
        locs.update((name, getattr(base, name)) for name in base_public)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get('routes.map')
        if mapper:
            locs['mapper'] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ('mapper', 'Routes mapper object')
        banner += "  %-10s -  %s\n" % ('wsgiapp',
            "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
            'paste.fixture wrapped around wsgiapp')

        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            try:
                try:
                    # 1.0 <= ipython
                    from IPython.terminal.embed import InteractiveShellEmbed
                except ImportError:
                    # 0.11 <= ipython < 1.0
                    from IPython.frontend.terminal.embed import InteractiveShellEmbed
                shell = InteractiveShellEmbed(banner2=banner)
            except ImportError:
                # ipython < 0.11
                from IPython.Shell import IPShellEmbed
                shell = IPShellEmbed(argv=self.args)
                shell.set_banner(shell.IP.BANNER + '\n\n' + banner)

            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            py_prefix = sys.platform.startswith('java') and 'J' or 'P'
            newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % \
                (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()
Example #5
0
def load_and_run_tshell() -> None:
    """Launch a shell for a thrift service."""

    sys.path.append(os.getcwd())

    parser = argparse.ArgumentParser(
        description=
        "Open a shell for a Thrift service with app configuration loaded.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument("--debug",
                        action="store_true",
                        default=False,
                        help="enable extra-verbose debug logging")
    parser.add_argument(
        "--app-name",
        default="main",
        metavar="NAME",
        help="name of app to load from config_file (default: main)",
    )
    parser.add_argument("config_file",
                        type=argparse.FileType("r"),
                        help="path to a configuration file")

    args = parser.parse_args(sys.argv[1:])
    with args.config_file:
        config = read_config(args.config_file,
                             server_name=None,
                             app_name=args.app_name)
    logging.basicConfig(level=logging.INFO)

    env = dict()
    env_banner = {
        "app": "This project's app instance",
        "context": "The context for this shell instance's span",
    }

    app = make_app(config.app)
    env["app"] = app

    baseplate: Baseplate = app.baseplate  # type: ignore
    context = baseplate.make_context_object()
    span = baseplate.make_server_span(context, "shell")
    env["context"] = span.context

    if config.tshell and "setup" in config.tshell:
        setup = _load_factory(config.tshell["setup"])
        setup(env, env_banner)

    # generate banner text
    banner = "Available Objects:\n"
    for var in sorted(env_banner.keys()):
        banner += "\n  {:<12} {}".format(var, env_banner[var])

    try:
        # try to use IPython if possible
        from IPython.terminal.embed import InteractiveShellEmbed
        from IPython.core.interactiveshell import DummyMod

        shell = InteractiveShellEmbed(banner2=banner)
        shell(local_ns=env, module=DummyMod())
    except ImportError:
        import code

        newbanner = f"Baseplate Interactive Shell\nPython {sys.version}\n\n"
        banner = newbanner + banner

        # import this just for its side-effects (of enabling nice keyboard
        # movement while editing text)
        try:
            import readline

            del readline
        except ImportError:
            pass

        shell = code.InteractiveConsole(locals=env)
        shell.interact(banner)
Example #6
0
def attach(active):
    """
    Enter a python shell with contracts and blockchain client
    available.
    """
    project_dir = os.path.abspath(os.getcwd())
    contracts_meta = utils.load_contracts(project_dir)
    client = Client('127.0.0.1', '8545')

    context = {
        'contracts': package_contracts(contracts_meta),
        'client': client,
    }
    data_dir = None
    if active:
        data_dir = get_active_data_dir(project_dir)
        if os.path.islink(data_dir):
            setup_known_instances(context, data_dir)
        else:
            click.echo(
                click.style("No Valid Active Chain Data Directory Found!",
                            fg="red"))

    def redeploy(contracts=[], record=True):
        return (deploy_set(context,
                           client,
                           project_dir,
                           data_dir=data_dir,
                           record=record,
                           contracts_by_name=contracts))

    context["redeploy"] = redeploy

    contract_names = ', '.join(sorted(contracts_meta.keys()))

    banner = textwrap.dedent("""
        Python: {python_version}

        Populus: v{populus_version}

        Project Path: {project_dir}

        contracts  -> Contract classes
        client     -> Blockchain client ({client_type})
        redeploy   -> Method to re-deploy project contracts
                      Example:
                        deployed_cts = redeploy()
                        deployed_cts = redeploy(record = False)
                        deployed_cts = redeploy(contracts = ["Example"])

        Contracts: {contracts}
        Check contracts.<type>.known for deployed contracts.

        """).format(
        python_version=sys.version.partition('\n')[0],
        populus_version=populus.__version__,
        project_dir=project_dir,
        client_type="json-rpc",
        contracts=click.wrap_text(
            contract_names,
            initial_indent='',
            subsequent_indent=' ' * 4,
        ),
    ).strip()

    if is_ipython:
        shell = InteractiveConsole(user_ns=context)
    else:
        shell = InteractiveConsole(context)

    # Start the active directory link observer
    event_handler = ActiveDataDirChangedEventHandler(
        project_dir=project_dir,
        context=context,
    )
    observer = get_active_dir_observer(project_dir, event_handler)

    observer.start()
    shell.interact(banner)
    observer.stop()
    observer.join()
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        # Determine the package name from the pylons.config object
        pkg_name = pylons.config['pylons.package']

        # Start the rest of our imports now that the app is loaded
        if is_minimal_template(pkg_name, True):
            model_module = None
            helpers_module = pkg_name + '.helpers'
            base_module = pkg_name + '.controllers'
        else:
            model_module = pkg_name + '.model'
            helpers_module = pkg_name + '.lib.helpers'
            base_module = pkg_name + '.lib.base'

        if model_module and can_import(model_module):
            locs['model'] = sys.modules[model_module]

        if can_import(helpers_module):
            locs['h'] = sys.modules[helpers_module]

        exec(
            'from pylons import app_globals, config, request, response, '
            'session, tmpl_context, url') in locs
        exec('from pylons.controllers.util import abort, redirect') in locs
        exec 'from pylons.i18n import _, ungettext, N_' in locs
        locs.pop('__builtins__', None)

        # Import all objects from the base module
        __import__(base_module)

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not \
                       __name.startswith('_') or __name == '_']
        locs.update((name, getattr(base, name)) for name in base_public)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get('routes.map')
        if mapper:
            locs['mapper'] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ('mapper', 'Routes mapper object')
        banner += "  %-10s -  %s\n" % ('wsgiapp',
                                       "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
                                       'paste.fixture wrapped around wsgiapp')

        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            try:
                try:
                    # 1.0 <= ipython
                    from IPython.terminal.embed import InteractiveShellEmbed
                except ImportError:
                    # 0.11 <= ipython < 1.0
                    from IPython.frontend.terminal.embed import InteractiveShellEmbed
                shell = InteractiveShellEmbed(banner2=banner)
            except ImportError:
                # ipython < 0.11
                from IPython.Shell import IPShellEmbed
                shell = IPShellEmbed(argv=self.args)
                shell.set_banner(shell.IP.BANNER + '\n\n' + banner)

            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            py_prefix = sys.platform.startswith('java') and 'J' or 'P'
            newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % \
                (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()