Example #1
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.'
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))
Example #3
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
Example #4
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
Example #5
0
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
Example #6
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
Example #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)
Example #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()
Example #9
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
Example #10
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))
Example #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()
Example #12
0
    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()
Example #13
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)
Example #14
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()
Example #15
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()
Example #16
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()
Example #17
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()
Example #18
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()
Example #19
0
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()
Example #20
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))
Example #21
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('')
Example #22
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('')
 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'])
 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)
 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'])
 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)
Example #27
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()
Example #28
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()
Example #29
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()
Example #30
0
    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()
Example #31
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()
Example #32
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
Example #33
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()
Example #34
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()
Example #35
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:
        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()
Example #37
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})
Example #38
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
    """
    # 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:
        thread = ManageThread(command, args=args)
        thread.start()
Example #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)
    
    # 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()
Example #40
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})
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()
Example #42
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
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, 'aldryn_segmentation')
    utility = ManagementUtility(argv)
    utility.execute()
Example #44
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()
Example #45
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()
Example #46
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()
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()
Example #48
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
Example #49
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
Example #50
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_daemon: Creates a new process for the command
    :param as_thread: Runs command in thread and returns immediately
    """
    
    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()
Example #51
0
    def application_tests(self):
        self.log_header('Application tests:')

        try:
            import django  # noqa
        except ImportError:
            print('Are you in a activated virtualenv and have installed the requirements?')
            print('virtualenv --python=/usr/bin/python3 tmp;source ./tmp/bin/activate;\
                pip install -r web_frontend/requirements/local.txt')
            return
        work_dir = os.getcwd()
        try:
            osmaxx_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'web_frontend')
            sys.path.append(osmaxx_path)
            os.chdir(osmaxx_path)
            os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings.test'
            utility = ManagementUtility(['manage.py', 'test'])
            utility.execute()
        except subprocess.CalledProcessError as e:
            logger.info(e.output.decode())
            self.log_failure("Tests failed. Please have a look at the {logfile};!".format(logfile=LOGFILE))
        finally:
            os.chdir(work_dir)
	def SvcDoRun(self):
		sys.stdout = open(os.path.join(project_dir, 'log', 'harmonyserv.log'      ), 'at', buffering=0)
		sys.stderr = open(os.path.join(project_dir, 'log', 'harmonyserv.error.log'), 'at', buffering=0)
		
		host = HOST
		port = PORT
		
		if port is None:
			try:
				port = int(host)
				host = None
			except:
				pass

		if host is None:
			if HOST is None:
				import socket
				host = socket.gethostbyname(socket.gethostname())
			else:
				host = HOST

		setup_environ(settings)
		utility = ManagementUtility([sys.argv[0], 'runserver', '%s:%s' % (host, port or PORT), '--noreload'])
		utility.execute()
Example #53
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.
    """
    setup_environ(settings_mod)
    # Set up Green Plum Database Features
    execfile(os.path.abspath(os.path.join(os.path.dirname(__file__), 'greenplum_monkey_patch.py')))
    if os.getpid() - os.getppid() == 1:  # Let Run-Server print the notifications once on the console
        sys.stdout.write("Applying Green plum Monkey Patch...Success\n")
        sys.stdout.flush()
    # END Set up Green Plum Database Features
    utility = ManagementUtility(argv)
    if 'syncdb' in sys.argv:
        from django import get_version
        from django.core.management import LaxOptionParser
        from django.core.management.commands import syncdb
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=get_version(),
                                 option_list=syncdb.Command.option_list)
        options = parser.parse_args(sys.argv)[0]
        create_schema_before_syncdb(**options.__dict__)
        # create_views_on_piggy_back_keys()
    utility.execute()
Example #54
0
#!/usr/bin/env python
import os
from django.core.management import setup_environ, ManagementUtility
try:
    import settings # Assumed to be in the same directory.
except ImportError:
    import sys
    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
    sys.exit(1)

if __name__ == "__main__":
    setup_environ(settings, original_settings_path=os.environ.get('DJANGO_SETTINGS_MODULE', 'settings'))
    utility = ManagementUtility(None)
    utility.execute()
Example #55
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()
def main(settings):
    setup_django(settings)
    utility = ManagementUtility(sys.argv)
    utility.execute()