예제 #1
0
def manage(command, args=[], in_background=False):
    """
    Run a django command on the kalite project

    :param command: The django command string identifier, e.g. 'runserver'
    :param args: List of options to parse to the django management command
    :param in_background: Creates a sub-process for the command
    """
    # Ensure that django.core.management's global _command variable is set
    # before call commands, especially the once that run in the background
    get_commands()
    # Import here so other commands can run faster
    if not in_background:
        utility = ManagementUtility([os.path.basename(sys.argv[0]), command] + args)
        # This ensures that 'kalite' is printed in help menus instead of
        # 'kalitectl.py' (a part from the top most text in `kalite manage help`
        utility.prog_name = 'kalite manage'
        utility.execute()
    else:
        if os.name != "nt":
            thread = ManageThread(command, args=args, name=" ".join([command]+args))
            thread.start()
        else:
            # TODO (aron): for versions > 0.13, see if we can just have everyone spawn another process (Popen vs. ManageThread)
            Popen([sys.executable, os.path.abspath(sys.argv[0]), "manage", command] + args, creationflags=CREATE_NEW_PROCESS_GROUP)
예제 #2
0
파일: tests.py 프로젝트: abdulhaq-e/django
 def _run_autocomplete(self):
     util = ManagementUtility(argv=sys.argv)
     try:
         util.autocomplete()
     except SystemExit:
         pass
     return self.output.getvalue().strip().split("\n")
예제 #3
0
    def run(self, project_name=None, dest_dir=None):
        # Make sure given name is not already in use by another python package/module.
        try:
            __import__(project_name)
        except ImportError:
            pass
        else:
            sys.exit("'%s' conflicts with the name of an existing "
                     "Python module and cannot be used as a project "
                     "name. Please try another name." % project_name)

        print("Creating a CodeRed CMS project called %(project_name)s" %
              {'project_name': project_name})  # noqa

        # Create the project from the Wagtail template using startapp

        # First find the path to Wagtail
        import coderedcms
        codered_path = os.path.dirname(coderedcms.__file__)
        template_path = os.path.join(codered_path, 'project_template')

        # Call django-admin startproject
        utility_args = [
            'django-admin.py', 'startproject', '--template=' + template_path,
            '--ext=html,rst', '--name=Dockerfile', project_name
        ]

        if dest_dir:
            utility_args.append(dest_dir)

        utility = ManagementUtility(utility_args)
        utility.execute()

        print("Success! %(project_name)s has been created" %
              {'project_name': project_name})  # noqa
예제 #4
0
파일: reset_db.py 프로젝트: tperrier/mwachx
    def handle(self,*args,**options):

        #Delete old DB
        print 'Deleting old sqlite db....'
        try:
            if settings.ON_OPENSHIFT:
                os.remove(os.path.join(os.environ['OPENSHIFT_DATA_DIR'],'mwach.db'))
            else:
                os.remove(os.path.join(settings.PROJECT_PATH,'mwach.db'))
        except OSError:
            pass

        if not os.path.isfile(JSON_DATA_FILE):
            sys.exit('JSON file %s Does Not Exist'%(JSON_DATA_FILE,))

        #Migrate new models
        print 'Migrating new db....'
        utility = ManagementUtility(['reset_db.py','migrate'])
        utility.execute()

        #Turn off Autocommit
        #transaction.set_autocommit(False)

        config.CURRENT_DATE = datetime.date.today()
        with transaction.atomic():
            create_backend()

            if options['participants'] > 0:
                load_old_participants(options)

            if options['jennifer']:
                add_jennifers()
예제 #5
0
    def cmd_e2e(
        self,
        cmd: typing.Sequence[str],
        stdin: typing.Optional[typing.Union[io.StringIO, bytes]] = None,
        stdout: typing.Optional[io.StringIO] = None,
        stderr: typing.Optional[io.StringIO] = None,
    ) -> typing.Tuple[str, str]:
        """Call a management command the way manage.py does.

        Unlike call_command, this method also tests the argparse configuration of the called command.
        """
        stdout = stdout or io.StringIO()
        stderr = stderr or io.StringIO()
        if stdin is None:
            stdin = io.StringIO()

        if isinstance(stdin, io.StringIO):
            stdin_mock = mock.patch("sys.stdin", stdin)
        else:

            def _read_mock(size=None):  # type: ignore # pylint: disable=unused-argument
                return stdin

            # TYPE NOTE: mypy detects a different type, but important thing is its a context manager
            stdin_mock = mock.patch(  # type: ignore[assignment]
                "sys.stdin.buffer.read", side_effect=_read_mock
            )

        with stdin_mock, mock.patch("sys.stdout", stdout), mock.patch("sys.stderr", stderr):
            util = ManagementUtility(["manage.py"] + list(cmd))
            util.execute()

        return stdout.getvalue(), stderr.getvalue()
예제 #6
0
파일: cli.py 프로젝트: ruimalheiro/ka-lite
def manage(command, args=None, as_thread=False):
    """
    Run a django command on the kalite project

    :param command: The django command string identifier, e.g. 'runserver'
    :param args: List of options to parse to the django management command
    :param as_thread: Runs command in thread and returns immediately
    """

    if not args:
        args = []

    args = update_default_args(["--traceback"], args)

    if not as_thread:
        utility = ManagementUtility([os.path.basename(sys.argv[0]), command] + args)
        # This ensures that 'kalite' is printed in help menus instead of
        # 'kalite' or 'kalite.__main__' (a part from the top most text in `kalite manage help`
        utility.prog_name = 'kalite manage'
        utility.execute()
    else:
        get_commands()  # Needed to populate the available commands before issuing one in a thread
        thread = ManageThread(command, args=args, name=" ".join([command] + args))
        thread.start()
        return thread
예제 #7
0
def manage(command, args=[], in_background=False):
    """
    Run a django command on the kalite project

    :param command: The django command string identifier, e.g. 'runserver'
    :param args: List of options to parse to the django management command
    :param in_background: Creates a sub-process for the command
    """
    # Ensure that django.core.management's global _command variable is set
    # before call commands, especially the once that run in the background
    get_commands()
    # Import here so other commands can run faster
    if not in_background:
        utility = ManagementUtility([os.path.basename(sys.argv[0]), command] +
                                    args)
        # This ensures that 'kalite' is printed in help menus instead of
        # 'kalitectl.py' (a part from the top most text in `kalite manage help`
        utility.prog_name = 'kalite manage'
        utility.execute()
    else:
        if os.name != "nt":
            thread = ManageThread(command,
                                  args=args,
                                  name=" ".join([command] + args))
            thread.start()
        else:
            # TODO (aron): for versions > 0.13, see if we can just have everyone spawn another process (Popen vs. ManageThread)
            Popen([
                sys.executable,
                os.path.abspath(sys.argv[0]), "manage", command
            ] + args,
                  creationflags=CREATE_NEW_PROCESS_GROUP)
예제 #8
0
def start (args):
    # if a specific conf has been provided (which it
    # will be), if we're inside the django reloaded
    if "RAPIDSMS_INI" in os.environ:
        ini = os.environ["RAPIDSMS_INI"]
    
    # use a local ini (for development)
    # if one exists, to avoid everyone
    # having their own rapidsms.ini
    elif os.path.isfile("local.ini"):
        ini = "local.ini"
    
    # otherwise, fall back
    else: ini = "rapidsms.ini"

    # add the ini path to the environment, so we can
    # access it globally, including any subprocesses
    # spawned by django
    os.environ["RAPIDSMS_INI"] = ini
    os.environ["DJANGO_SETTINGS_MODULE"] = "rapidsms.webui.settings"

    # read the config, which is shared
    # between the back and frontend
    conf = Config(ini)
    
    # if we found a config ini, try to configure Django
    if conf.sources:
        # This builds the django config from rapidsms.config, in a 
        # round-about way.
        # Can't do it until env[RAPIDSMS_INI] is defined
        from rapidsms.webui import settings 
        
        import_local_settings(settings, ini)

        # whatever we're doing, we'll need to call
        # django's setup_environ, to configure the ORM
        
        from django.core.management import setup_environ, execute_manager
        setup_environ(settings)
    else:
        settings = None

    # if one or more arguments were passed, we're
    # starting up django -- copied from manage.py
    if len(args) < 2:
        print "Commands: route, startproject <name>, startapp <name>"
        sys.exit(1)

    if hasattr(Manager, args[1]):
        handler = getattr(Manager(), args[1])
        handler(conf, *args[2:])
    elif settings:
        # none of the commands were recognized,
        # so hand off to Django
        
        from django.core.management import ManagementUtility
        # The following is equivalent to django's "execute_manager(settings)"
        # only without overriding RapidSMS webui settings
        utility = ManagementUtility()
        utility.execute()
예제 #9
0
def report_data(dumper):
    """
    Fetches data from management commands and reports it to dumper.

    :type dumper _xml.XmlDumper
    :param dumper: destination to report
    """
    utility = ManagementUtility()
    for command_name in get_commands().keys():
        try:
            command = utility.fetch_command(command_name)
        except ImproperlyConfigured:
            continue  # TODO: Log somehow

        assert isinstance(command, BaseCommand)

        use_argparse = False
        try:
            use_argparse = command.use_argparse
        except AttributeError:
            pass
        dumper.start_command(command_name=command_name,
                             command_help_text=str(command.usage("").replace("%prog", command_name)))
        module_to_use = _argparse if use_argparse else _optparse # Choose appropriate module: argparse, optparse
        module_to_use.process_command(dumper, command, command.create_parser("", command_name))
        dumper.close_command()
예제 #10
0
def manage(command, args=[], as_thread=False):
    """
    Run a django command on the kalite project

    :param command: The django command string identifier, e.g. 'runserver'
    :param args: List of options to parse to the django management command
    :param as_thread: Runs command in thread and returns immediately
    """

    args = update_default_args(["--traceback"], args)

    if not as_thread:
        if PROFILE:
            profile_memory()

        utility = ManagementUtility([os.path.basename(sys.argv[0]), command] + args)
        # This ensures that 'kalite' is printed in help menus instead of
        # 'kalitectl.py' (a part from the top most text in `kalite manage help`
        utility.prog_name = 'kalite manage'
        utility.execute()
    else:
        get_commands()  # Needed to populate the available commands before issuing one in a thread
        thread = ManageThread(command, args=args, name=" ".join([command] + args))
        thread.start()
        return thread
예제 #11
0
 def run(self):
     utility = ManagementUtility(
         [os.path.basename(sys.argv[0]), self.command] + self.args)
     # This ensures that 'kalite' is printed in help menus instead of
     # 'kalitectl.py' (a part from the top most text in `kalite manage help`
     utility.prog_name = 'kalite manage'
     utility.execute()
예제 #12
0
    def run(self, project_name=None, dest_dir=None):
        # Make sure given name is not already in use by another python package/module.
        try:
            __import__(project_name)
        except ImportError:
            pass
        else:
            sys.exit("'%s' conflicts with the name of an existing "
                     "Python module and cannot be used as a project "
                     "name. Please try another name." % project_name)

        print("Creating a Wagtail project called %(project_name)s" % {'project_name': project_name})  # noqa

        # Create the project from the Wagtail template using startapp

        # First find the path to Wagtail
        import wagtail
        wagtail_path = os.path.dirname(wagtail.__file__)
        template_path = os.path.join(wagtail_path, 'project_template')

        # Call django-admin startproject
        utility_args = ['django-admin.py',
                        'startproject',
                        '--template=' + template_path,
                        '--ext=html,rst',
                        '--name=Dockerfile',
                        project_name]

        if dest_dir:
            utility_args.append(dest_dir)

        utility = ManagementUtility(utility_args)
        utility.execute()

        print("Success! %(project_name)s has been created" % {'project_name': project_name})  # noqa
예제 #13
0
    def run(self, project_name=None, dest_dir=None):
        # Make sure given name is not already in use by another python package/module.
        try:
            __import__(project_name)
        except ImportError:
            pass
        else:
            sys.exit("'%s' conflicts with the name of an existing "
                     "Python module and cannot be used as a project "
                     "name. Please try another name." % project_name)

        print("Creating a Tendenci project called %(project_name)s" %
              {'project_name': project_name})  # noqa

        # First find the path to Tendenci
        template_path = "https://github.com/tendenci/tendenci-project-template/archive/master.zip"

        # Call django-admin startproject
        utility_args = [
            'django-admin.py', 'startproject', '--template=' + template_path,
            project_name
        ]

        #if dest_dir:
        #utility_args.append(dest_dir)

        utility = ManagementUtility(utility_args)
        utility.execute()

        print("Success! %(project_name)s has been created" %
              {'project_name': project_name})  # noqa
def create_project(project_name):
    """Create the project using the Django startproject command"""

    print("Creating a Wagtail project called {project_name}".format(
        project_name=project_name))

    import wagtailstartproject
    wagtailstartproject_path = os.path.dirname(wagtailstartproject.__file__)

    template_path = os.path.join(wagtailstartproject_path, 'project_template')

    # Call django-admin startproject
    utility_args = [
        'django-admin.py', 'startproject', '--template=' + template_path,
        '--extension=py,ini,html,rst,json,cfg', project_name
    ]

    # always put the project template inside the current directory:
    utility_args.append('.')

    utility = ManagementUtility(utility_args)
    utility.execute()

    print("Success! {project_name} has been created".format(
        project_name=project_name))
예제 #15
0
def create_project(args):
    """
    Create a new django project using the longclaw template
    """

    # Make sure given name is not already in use by another python package/module.
    try:
        __import__(args.project_name)
    except ImportError:
        pass
    else:
        sys.exit("'{}' conflicts with the name of an existing "
                 "Python module and cannot be used as a project "
                 "name. Please try another name.".format(args.project_name))

    # Get the longclaw template path
    template_path = path.join(path.dirname(longclaw.__file__),
                              'project_template')

    utility = ManagementUtility(
        ('django-admin.py', 'startproject',
         '--template={}'.format(template_path), '--ext=html,css,js,py,txt',
         args.project_name))
    utility.execute()
    print("{} has been created.".format(args.project_name))
예제 #16
0
    def handle(self, *args, **options):
        """
        Run and profile the specified management command with the provided
        arguments.
        """
        if not len(args):
            self.print_help(sys.argv[0], 'profile')
            sys.exit(1)
        if not options['sort'] and not options['path']:
            self.stdout.write('Output file path is required for call graph generation')
            sys.exit(1)

        command_name = args[0]
        utility = ManagementUtility(sys.argv)
        command = utility.fetch_command(command_name)
        parser = command.create_parser(sys.argv[0], command_name)
        command_options, command_args = parser.parse_args(list(args[1:]))

        if command_name == 'test' and settings.TEST_RUNNER == 'django_nose.NoseTestSuiteRunner':
            # Ugly hack: make it so django-nose won't have nosetests choke on
            # our parameters
            BaseCommand.option_list += self.custom_options

        if options['backend'] == 'yappi':
            import yet_another_django_profiler.yadp_yappi as yadp_yappi
            profiler = yadp_yappi.YappiProfile()
        else:
            profiler = cProfile.Profile()

        atexit.register(output_results, profiler, options, self.stdout)
        profiler.runcall(call_command, command_name, *command_args, **command_options.__dict__)
        sys.exit(0)
예제 #17
0
def report_data(dumper):
    """
    Fetches data from management commands and reports it to dumper.

    :type dumper _xml.XmlDumper
    :param dumper: destination to report
    """
    utility = ManagementUtility()
    for command_name in get_commands().keys():
        command = utility.fetch_command(command_name)
        assert isinstance(command, BaseCommand)
        dumper.start_command(
            command_name=command_name,
            command_help_text=str(command.usage("").replace("%prog", command_name)),  # TODO: support subcommands
            command_args_text=str(command.args),
        )
        for opt in command.option_list:
            opt_type = opt.type if opt.type in Option.TYPES else ""  # Empty for unknown
            # There is no official way to access this field, so I use protected one. At least it is public API.
            # noinspection PyProtectedMember
            dumper.add_command_option(
                opt_type=opt_type,
                choices=opt.choices,
                long_opt_names=opt._long_opts,
                short_opt_names=opt._short_opts,
                help_text=opt.help,
                num_of_args=opt.nargs,
            )
        dumper.close_command()
예제 #18
0
def report_data(dumper):
    """
    Fetches data from management commands and reports it to dumper.

    :type dumper _xml.XmlDumper
    :param dumper: destination to report
    """
    utility = ManagementUtility()
    for command_name in get_commands().keys():
        try:
            command = utility.fetch_command(command_name)
        except Exception:
            continue  # TODO: Log somehow. Probably print to output?

        assert isinstance(command, BaseCommand)

        use_argparse = False
        try:
            use_argparse = command.use_argparse
        except AttributeError:
            pass
        dumper.start_command(command_name=command_name,
                             command_help_text=str(
                                 command.usage("").replace(
                                     "%prog", command_name)))
        module_to_use = _argparse if use_argparse else _optparse  # Choose appropriate module: argparse, optparse
        module_to_use.process_command(dumper, command,
                                      command.create_parser("", command_name))
        dumper.close_command()
예제 #19
0
 def _run_autocomplete(self):
     util = ManagementUtility(argv=sys.argv)
     try:
         util.autocomplete()
     except SystemExit:
         pass
     return self.output.getvalue().strip().split('\n')
예제 #20
0
 def _run(coor, argv):
     global urlpatterns
     urlpatterns = patterns('',
         url('.*', coor or DjangoCoor())
     )
     os.environ['DJANGO_SETTINGS_MODULE'] = __name__
     utility = ManagementUtility(sys.argv[:1] + argv)
     utility.execute()
예제 #21
0
 def run_command(self, command, *args, **kwargs):
     """
     Runs a Django command.
     """
     self.init_project()
     argv = ['nina cmd', command, *map(str, args), *to_argv(**kwargs)]
     utility = ManagementUtility(argv)
     utility.execute()
예제 #22
0
파일: __init__.py 프로젝트: rafamanzo/colab
def execute_from_command_line(argv=None):
    """
    A simple method that runs a ManagementUtility.
    """
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "colab.settings")

    utility = ManagementUtility(argv)
    utility.execute()
예제 #23
0
 def _run_autocomplete(self):
     util = ManagementUtility(argv=sys.argv)
     with captured_stdout() as stdout:
         try:
             util.autocomplete()
         except SystemExit:
             pass
     return stdout.getvalue().strip().split('\n')
예제 #24
0
def update_migrations():
    """
    Creates schemamigrations for sentry.
    """
    from django.core.management import ManagementUtility
    args = 'manage.py schemamigration sentry --auto'.split(' ')
    utility = ManagementUtility(args)
    utility.execute()
예제 #25
0
def update_migrations():
    """
    Creates schemamigrations for localshop.
    """
    from django.core.management import ManagementUtility
    args = 'manage.py schemamigration localshop --auto'.split(' ')
    utility = ManagementUtility(args)
    utility.execute()
예제 #26
0
파일: tests.py 프로젝트: yephper/django
 def _run_autocomplete(self):
     util = ManagementUtility(argv=sys.argv)
     with captured_stdout() as stdout:
         try:
             util.autocomplete()
         except SystemExit:
             pass
     return stdout.getvalue().strip().split('\n')
예제 #27
0
def create_project(parser, options, args):
    # Validate args
    if len(args) < 2:
        parser.error('Please specify a name for your Arctic installation')
    elif len(args) > 3:
        parser.error('Too many arguments')

    project_name = args[1]
    try:
        dest_dir = args[2]
    except IndexError:
        dest_dir = ''

    # Make sure given name is not already in use by another
    # python package/module.
    try:
        __import__(project_name)
    except ImportError:
        pass
    else:
        parser.error('"{}" conflicts with the name of an existing '
                     'Python module and cannot be used as a project '
                     'name. Please try another name.'.format(project_name))

    print('Creating an Arctic project named {}'.format(project_name))

    # Create the project from the Arctic template using startapp

    # First find the path to Arctic
    import arctic
    arctic_path = os.path.dirname(arctic.__file__)
    template_path = os.path.join(arctic_path, 'project_template')

    # Call django-admin startproject
    utility_args = [
        'django-admin.py', 'startproject', '--template=' + template_path,
        '--ext=html,rst', project_name
    ]

    if dest_dir:
        utility_args.append(dest_dir)

    utility = ManagementUtility(utility_args)
    utility.execute()

    # add execute permission to manage.py, somehow it gets lost on the way
    manage_py = os.path.join(dest_dir or project_name, 'manage.py')
    st = os.stat(manage_py)
    os.chmod(manage_py,
             st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)

    print('Congratulations! {0} has been created.\n'
          'The next steps are:\n'
          '- In config/settings.py change the database settings (if needed).\n'
          '- Run database migrations: {0}/manage.py migrate.\n'
          '- Create an admin user: {0}/manage.py createsuperuser.\n'
          '- Finally run the project: {0}/manage.py runserver.\n'.format(
              project_name))
예제 #28
0
 def run_management_command(self, *args):
     from django.core.management import ManagementUtility
     args = ['manage.py'] + list(args)
     utility = ManagementUtility(args)
     try:
         utility.execute()
     except SystemExit:
         pass
     print('')
예제 #29
0
 def run_management_command(self, *args):
     from django.core.management import ManagementUtility
     args = ['manage.py'] + list(args)
     utility = ManagementUtility(args)
     try:
         utility.execute()
     except SystemExit:
         pass
     print('')
예제 #30
0
 def test_version_is_printed_once(self):
     args = ['manage.py', '--version']
     utility = ManagementUtility(argv=args)
     self.begin_capture()
     try:
         utility.execute()
     finally:
         self.end_capture()
     expected = get_version()
     self.assertTrue(self.capture['stdout'].count(expected) == 1)
예제 #31
0
 def test_version_is_printed_once(self):
     args = ['manage.py', '--version']
     utility = ManagementUtility(argv=args)
     self.begin_capture()
     try:
         utility.execute()
     finally:
         self.end_capture()
     expected = get_version()
     self.assertTrue(self.capture['stdout'].count(expected) == 1)
예제 #32
0
 def test_update_settings(self):
     self.assertTrue(settings.DEBUG)
     args = ['manage.py', 'settings', '--django_debug=False', 'DEBUG']
     utility = ManagementUtility(argv=args)
     self.begin_capture()
     try:
         utility.execute()
     finally:
         self.end_capture()
     self.assertTrue('False' in self.capture['stdout'])
예제 #33
0
 def test_update_settings(self):
     self.assertTrue(settings.DEBUG)
     args = ['manage.py', 'settings', '--django_debug=False', 'DEBUG']
     utility = ManagementUtility(argv=args)
     self.begin_capture()
     try:
         utility.execute()
     finally:
         self.end_capture()
     self.assertTrue('False' in self.capture['stdout'])
예제 #34
0
def runtests(*test_args):

    parent = os.path.dirname(os.path.abspath(__file__))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'consent.tests.settings'
    sys.path.insert(0, parent)

    from django.core.management import ManagementUtility

    utility = ManagementUtility()
    command = utility.fetch_command('test')
    command.execute(verbosity=1)
    sys.exit()
예제 #35
0
def execute_from_command_line(argv=None):
    """
    A simple method that runs a ManagementUtility.
    """
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "colab.settings")
    from django.conf import settings

    if not hasattr(settings, 'SECRET_KEY') and 'initconfig' in sys.argv:
        command = initconfig.Command()
        command.handle()
    else:
        utility = ManagementUtility(argv)
        utility.execute()
예제 #36
0
    def cmd_help_text(self, cmd: str) -> str:
        """Get the help message for a given management command.

        Also asserts that stderr is empty and the command exists with status code 0."""
        stdout = io.StringIO()
        stderr = io.StringIO()
        with mock.patch("sys.stdout", stdout), mock.patch("sys.stderr", stderr):
            util = ManagementUtility(["manage.py", cmd, "--help"])
            with self.assertSystemExit(0):
                util.execute()

        self.assertEqual(stderr.getvalue(), "")
        return stdout.getvalue()
예제 #37
0
    def handle(self, *args, **options):
        """
        Run and profile the specified management command with the provided
        arguments.
        """
        if not self.use_argparse and not len(args):
            self.print_help(sys.argv[0], 'profile')
            sys.exit(1)
        if not options['sort'] and not options['path']:
            self.stdout.write(
                'Output file path is required for call graph generation')
            sys.exit(1)

        if self.use_argparse:
            command_name = options['other_command']
        else:
            command_name = args[0]
        utility = ManagementUtility(sys.argv)
        command = utility.fetch_command(command_name)
        parser = command.create_parser(sys.argv[0], command_name)
        if self.use_argparse:
            command_options = parser.parse_args(options['command_arguments'])
            command_args = vars(command_options).pop('args', ())
        else:
            command_options, command_args = parser.parse_args(list(args[1:]))

        if command_name == 'test' and django_settings.TEST_RUNNER == 'django_nose.NoseTestSuiteRunner':
            # Ugly hack: make it so django-nose won't have nosetests choke on
            # our parameters
            BaseCommand.option_list += self.custom_options

        if options['backend'] == 'yappi' or (settings.YADP_PROFILER_BACKEND
                                             == 'yappi'
                                             and not options['backend']):
            import yet_another_django_profiler.yadp_yappi as yadp_yappi
            profiler = yadp_yappi.YappiProfile(wall=options['clock'] == 'wall')
        else:
            profiler = cProfile.Profile()

        if 'testing' not in options:
            atexit.register(output_results, profiler, options, self.stdout)
        profiler.runcall(call_command,
                         command_name,
                         *command_args,
                         stderr=self.stderr,
                         stdout=self.stdout,
                         **vars(command_options))
        if 'testing' in options:
            output_results(profiler, options, self.stdout)
        else:
            sys.exit(0)
예제 #38
0
 def handle_noargs(self, **options):
     utilityOne = ManagementUtility(['./manage.py', 'syncdb'])
     utilityOne.execute()
     
     utilityTwo = ManagementUtility(['./manage.py', 'loaddata', 'sample_data'])
     utilityTwo.execute()
     return 'Sample data loaded.'
예제 #39
0
def execute_manager(settings_mod, argv=None):
    """
    Like execute_from_command_line(), but for use by manage.py, a
    project-specific django-admin.py utility.
    """
    
    # don't add the project directory to the environment, as this ends
    # up importing classes using the project name, and self.assertIsInstance
    # requires us to specify the project name, making our tests non-portable.
    # setup_environ(settings_mod)
    
    import binder.monkeypatch
    utility = ManagementUtility(argv)
    utility.execute()
예제 #40
0
파일: base.py 프로젝트: yaka-es/django-ca
    def call_command(self, command, *argv, **kwargs):
        argv = ['manage.py'] + list(argv)
        utility = ManagementUtility(argv)
        command = utility.fetch_command(command)
        parser = command.create_parser('manage.py', command)
        options = parser.parse_args(argv[1:])
        cmd_options = vars(options)

        cmd_options.setdefault('stdout', StringIO())
        cmd_options.setdefault('stderr', StringIO())

        stdin = kwargs.pop('stdin', StringIO())
        with patch('sys.stdin', stdin):
            command.execute(**cmd_options)
        return cmd_options['stdout'].getvalue(), cmd_options['stderr'].getvalue()
예제 #41
0
파일: base.py 프로젝트: zwd1990/django-ca
    def cmd_e2e(self, cmd, stdin=None, stdout=None, stderr=None):
        """Call a management command the way manage.py does.

        Unlike call_command, this method also tests the argparse configuration of the called command.
        """
        stdout = stdout or StringIO()
        stderr = stderr or StringIO()
        if stdin is None:
            stdin = StringIO()

        with patch('sys.stdin', stdin), patch('sys.stdout', stdout), patch('sys.stderr', stderr):
            util = ManagementUtility(['manage.py', ] + list(cmd))
            util.execute()

        return stdout.getvalue(), stderr.getvalue()
예제 #42
0
    def start(self, args):
        project_name = args.project_name
        print('Gabo is starting {0}...'.format(project_name))
        PROJECT_PACKAGE = Path(__file__).resolve().parent.parent
        macondo_project_path = os.path.join(PROJECT_PACKAGE, 'macondo_project')

        django_args = [
            'django-admin.py',
            'startproject',
            '--template={0}'.format(macondo_project_path),
            project_name
        ]

        django_management = ManagementUtility(django_args)
        django_management.execute()
예제 #43
0
def create_project(parser, options, args):

    # Validate args
    if len(args) < 2:
        parser.error("Please specify a name for your Wagtail installation")
    elif len(args) > 3:
        print(args)
        parser.error("Too many arguments")

    project_name = args[1]
    try:
        dest_dir = args[2]
    except IndexError:
        dest_dir = None

    # Make sure given name is not already in use by another python package/module.
    try:
        __import__(project_name)
    except ImportError:
        pass
    else:
        parser.error("'%s' conflicts with the name of an existing "
                     "Python module and cannot be used as a project "
                     "name. Please try another name." % project_name)

    print("Creating a Wagtail project called %(project_name)s" % {'project_name': project_name})  # noqa

    # Create the project from the Wagtail template using startapp

    # First find the path to Wagtail
    import wagtail
    wagtail_path = os.path.dirname(wagtail.__file__)
    template_path = os.path.join(wagtail_path, 'project_template')

    # Call django-admin startproject
    utility_args = ['django-admin.py',
                    'startproject',
                    '--template=' + template_path,
                    '--ext=html,rst',
                    project_name]

    if dest_dir:
        utility_args.append(dest_dir)

    utility = ManagementUtility(utility_args)
    utility.execute()

    print("Success! %(project_name)s has been created" % {'project_name': project_name})  # noqa
예제 #44
0
def schemamigration():
    # turn ``schemamigration.py --initial`` into
    # ``manage.py schemamigration cmsplugin_disqus --initial`` and setup the
    # enviroment
    from django.conf import settings

    from django.core.management import ManagementUtility
    settings.configure(INSTALLED_APPS=INSTALLED_APPS,
                       ROOT_URLCONF=ROOT_URLCONF,
                       DATABASES=DATABASES,
                       TEMPLATE_CONTEXT_PROCESSORS=TEMPLATE_CONTEXT_PROCESSORS)
    argv = list(sys.argv)
    argv.insert(1, 'schemamigration')
    argv.insert(2, 'djangocms_style')
    utility = ManagementUtility(argv)
    utility.execute()
예제 #45
0
    def handle(self, *args, **kwargs):
        """
        Handle command execution
        :param args:
        :param kwargs:
        :return: None
        """
        args = [sys.argv[0], 'makemigrations']

        for app in settings.INSTALLED_APPS:
            app_dir = os.path.join(settings.BASE_DIR, app)
            if os.path.isdir(app_dir):
                args.append(app)

        utility = ManagementUtility(args)
        utility.execute()
예제 #46
0
파일: wagtail.py 프로젝트: bjesus/wagtail
def create_project(parser, options, args):
    # Validate args
    if len(args) < 2:
        parser.error("Please specify a name for your wagtail installation")
    elif len(args) > 3:
        parser.error("Too many arguments")

    project_name = args[1]
    try:
        dest_dir = args[2]
    except IndexError:
        dest_dir = None

    # Make sure given name is not already in use by another python package/module.
    try:
        __import__(project_name)
    except ImportError:
        pass
    else:
        parser.error("'%s' conflicts with the name of an existing "
                     "Python module and cannot be used as a project "
                     "name. Please try another name." % project_name)

    print("Creating a wagtail project called %(project_name)s" % {'project_name': project_name})

    # Create the project from the wagtail template using startapp

    # First find the path to wagtail
    import wagtail
    wagtail_path = os.path.dirname(wagtail.__file__)
    template_path = os.path.join(wagtail_path, 'project_template')

    # Call django-admin startproject
    utility_args = ['django-admin.py',
                    'startproject',
                    '--template=' + template_path,
                    '--name=Vagrantfile',
                    '--ext=html,rst',
                    project_name]

    if dest_dir:
        utility_args.append(dest_dir)

    utility = ManagementUtility(utility_args)
    utility.execute()

    print("Success! %(project_name)s is created" % {'project_name': project_name})
def schemamigration():
    # turn ``schemamigration.py --initial`` into
    # ``manage.py schemamigration cmsplugin_disqus --initial`` and setup the
    # enviroment
    from django.conf import settings

    from django.core.management import ManagementUtility
    settings.configure(
        INSTALLED_APPS=test_settings.INSTALLED_APPS,
        DATABASES=test_settings.DATABASES,
        TEMPLATE_CONTEXT_PROCESSORS=test_settings.TEMPLATE_CONTEXT_PROCESSORS,
        ROOT_URLCONF=test_settings.ROOT_URLCONF)
    argv = list(sys.argv)
    argv.insert(1, 'schemamigration')
    argv.insert(2, 'djangocms_text_ckeditor')
    utility = ManagementUtility(argv)
    utility.execute()
예제 #48
0
def execute_manager(settings_mod, argv=None):
    """
    Like execute_from_command_line(), but for use by manage.py, a
    project-specific django-admin.py utility.
    """
    
    # don't add the project directory to the environment, as this ends
    # up importing classes using the project name, and self.assertIsInstance
    # requires us to specify the project name, making our tests non-portable.
    # setup_environ(settings_mod)
    
    # No monkey patches yet :)
    # import binder.monkeypatch
    # But we do need to do this first:
    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

    utility = ManagementUtility(argv)
    utility.execute()
    def handle(self, *args, **options):
        """
        Run and profile the specified management command with the provided
        arguments.
        """
        if not self.use_argparse and not len(args):
            self.print_help(sys.argv[0], 'profile')
            sys.exit(1)
        if not options['sort'] and not options['path']:
            self.stdout.write('Output file path is required for call graph generation')
            sys.exit(1)

        if self.use_argparse:
            command_name = options['other_command']
        else:
            command_name = args[0]
        utility = ManagementUtility(sys.argv)
        command = utility.fetch_command(command_name)
        parser = command.create_parser(sys.argv[0], command_name)
        if self.use_argparse:
            command_options = parser.parse_args(options['command_arguments'])
            command_args = vars(command_options).pop('args', ())
        else:
            command_options, command_args = parser.parse_args(list(args[1:]))

        if command_name == 'test' and django_settings.TEST_RUNNER == 'django_nose.NoseTestSuiteRunner':
            # Ugly hack: make it so django-nose won't have nosetests choke on
            # our parameters
            BaseCommand.option_list += self.custom_options

        if options['backend'] == 'yappi' or (settings.YADP_PROFILER_BACKEND == 'yappi' and not options['backend']):
            import yet_another_django_profiler.yadp_yappi as yadp_yappi
            profiler = yadp_yappi.YappiProfile(wall=options['clock'] == 'wall')
        else:
            profiler = cProfile.Profile()

        if 'testing' not in options:
            atexit.register(output_results, profiler, options, self.stdout)
        profiler.runcall(call_command, command_name, *command_args, stderr=self.stderr,
                         stdout=self.stdout, **vars(command_options))
        if 'testing' in options:
            output_results(profiler, options, self.stdout)
        else:
            sys.exit(0)
예제 #50
0
def create_project(parser, options, args):
    # Validate args
    if len(args) < 2:
        parser.error("Please specify a name for your wagtail installation")
    elif len(args) > 2:
        parser.error("Too many arguments")

    project_name = args[1]

    # Make sure given name is not already in use by another python package/module.
    try:
        __import__(project_name)
    except ImportError:
        pass
    else:
        parser.error("'%s' conflicts with the name of an existing "
                     "Python module and cannot be used as a project "
                     "name. Please try another name." % project_name)

    # Make sure directory does not already exist
    if os.path.exists(project_name):
        print('A directory called %(project_name)s already exists. \
            Please choose another name for your wagtail project or remove the existing directory.' % {'project_name': project_name})
        sys.exit(errno.EEXIST)

    print("Creating a wagtail project called %(project_name)s" % {'project_name': project_name})

    # Create the project from the wagtail template using startapp

    # First find the path to wagtail
    import wagtail
    wagtail_path = os.path.dirname(wagtail.__file__)
    template_path = os.path.join(wagtail_path, 'project_template')

    # Call django-admin startproject
    utility = ManagementUtility([
        'django-admin.py', 'startproject',
        '--template=' + template_path,
        '--name=Vagrantfile', '--ext=html,rst',
        project_name
    ])
    utility.execute()

    print("Success! %(project_name)s is created" % {'project_name': project_name})
예제 #51
0
def schemamigration():
    # turn ``schemamigration.py --initial`` into
    # ``manage.py schemamigration cmsplugin_disqus --initial`` and setup the
    # enviroment

    from django.conf import settings
    from django.core.management import ManagementUtility

    settings.configure(
        INSTALLED_APPS=INSTALLED_APPS,
        DATABASES=DATABASES,
        TEMPLATE_CONTEXT_PROCESSORS=TEMPLATE_CONTEXT_PROCESSORS
    )

    argv = list(sys.argv)
    argv.insert(1, 'schemamigration')
    argv.insert(2, 'cmsplugin_articles')
    utility = ManagementUtility(argv)
    utility.execute()
예제 #52
0
def run_django_command(command, args):
    try:
        sys.path.append(path.join(MAIN_DIR, "server"));
        server_py = path.join(MAIN_DIR, "server", "manage.py")
        
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
        
        # Prepare argv
        argv = list(args)
        argv.insert(0, command)        
        argv.insert(0, server_py)
        
        from django.core.management import ManagementUtility
        commander = ManagementUtility(argv)
        commander.execute()
    except:
        print "There was an error running a the '%s' command with '%s'" % (command, args)
        sys.exit(1)
        
    return
예제 #53
0
def main():
    """
    django-develop CLI entry point.
    """
    # XXX: Bail out early if being invoked for autocompletion.
    utility = ManagementUtility()
    utility.autocomplete()

    if not utils.is_inside_virtual_env():
        _fail('Run django-develop inside a virtualenv')

    dd = _get_DjangoDevelop()

    if not dd.instance_path.exists():
        _fail('django-develop not configured, try "django-develop-config"')
    else:
        # Set up and hand over to Django
        dd.activate_dev_settings()

        utility.execute()
def schemamigration():

    #
    # turn ``schemamigration.py --initial`` into:
    #   ``manage.py schemamigration aldryn_segmentation --initial``
    # and setup the environment.
    #

    from django.conf import settings

    from django.core.management import ManagementUtility
    settings.configure(
        INSTALLED_APPS=INSTALLED_APPS,
        ROOT_URLCONF=ROOT_URLCONF,
        DATABASES=DATABASES,
        TEMPLATE_CONTEXT_PROCESSORS=TEMPLATE_CONTEXT_PROCESSORS
    )
    argv = list(sys.argv)
    argv.insert(1, 'schemamigration')
    argv.insert(2, 'country_segment')
    utility = ManagementUtility(argv)
    utility.execute()
예제 #55
0
def djangomigration():
    # turn ``djangomigration.py`` into
    # ``manage.py makemigrations djangocms_grid`` and setup the
    # environment
    from django.conf import settings

    from django.core.management import ManagementUtility
    settings.configure(
        INSTALLED_APPS=INSTALLED_APPS,
        ROOT_URLCONF=ROOT_URLCONF,
        DATABASES=DATABASES,
        TEMPLATE_CONTEXT_PROCESSORS=TEMPLATE_CONTEXT_PROCESSORS,
        MIGRATION_MODULES=MIGRATION_MODULES,
        LANGUAGE_CODE=LANGUAGE_CODE,
        LANGUAGES=LANGUAGES,
        SITE_ID=SITE_ID,
    )
    argv = list(sys.argv)
    argv.insert(1, 'makemigrations')
    argv.insert(2, 'djangocms_grid')
    utility = ManagementUtility(argv)
    utility.execute()
예제 #56
0
def run_django_command(command, args, require_settings = True):
    try:
        sys.path.append(path.join(MAIN_DIR, "server"));
        server_py = path.join(MAIN_DIR, "server", "manage.py")

        # Differentiates between those manage.py commands that require
        # a working settings.py, and those that can run without it, like 
        # startapp.
        if require_settings:
            os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
        
        # Prepare argv
        argv = list(args)
        argv.insert(0, command)        
        argv.insert(0, server_py)
        
        from django.core.management import ManagementUtility
        commander = ManagementUtility(argv)
        commander.execute()
    except Exception, e:
        print "There was an error running the '%s' command with '%s'." % (command, args)
        raise