Python django.core.management.CommandError() Examples

The following are 30 code examples for showing how to use django.core.management.CommandError(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.core.management , or try the search function .

Example 1
Project: django-anonymizer   Author: BetterWorks   File: check_anonymizers.py    License: MIT License 6 votes vote down vote up
def handle_app_config(self, app_config, **options):
        anonymizers = get_anonymizers(app_config)
        models = set()
        errors = []
        for klass in anonymizers:
            models.add(klass.model)
            instance = klass()
            try:
                instance.validate()
            except ValueError as e:
                errors.append(unicode(e))

        for model in app_config.get_models():
            if model._meta.abstract or model._meta.proxy:
                continue

            if model not in models:
                errors.append(u'need anonymizer for %s' % model)

        if errors:
            raise CommandError('%d errors\n%s' % (len(errors), '\n'.join(errors)))
        return 0 
Example 2
Project: desec-stack   Author: desec-io   File: sync-from-pdns.py    License: MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        domains = Domain.objects.all()

        if options['domain-name']:
            domains = domains.filter(name__in=options['domain-name'])
            domain_names = domains.values_list('name', flat=True)

            for domain_name in options['domain-name']:
                if domain_name not in domain_names:
                    raise CommandError('{} is not a known domain'.format(domain_name))

        for domain in domains:
            self.stdout.write('%s ...' % domain.name, ending='')
            try:
                self._sync_domain(domain)
                self.stdout.write(' synced')
            except Exception as e:
                self.stdout.write(' failed')
                msg = 'Error while processing {}: {}'.format(domain.name, e)
                raise CommandError(msg) 
Example 3
Project: linkedevents   Author: City-of-Helsinki   File: city_sdk.py    License: MIT License 6 votes vote down vote up
def authenticate(self):
        """
        Authenticate, CitySDK uses session based username/password auth
        """
        username = settings.CITYSDK_API_SETTINGS['USERNAME']
        password = settings.CITYSDK_API_SETTINGS['PASSWORD']
        session_response = requests.get(
            '%sauth?username=%s&password=%s' %
            (BASE_API_URL, username, password))
        if session_response.status_code == 200:
            self.session_cookies = session_response.cookies
            print("Authentication successful with response: %s"
                  % session_response.text)
        else:
            raise CommandError(
                "Authentication failed with credentials %s:%s" % (
                    (username, password)
                )) 
Example 4
Project: casepro   Author: rapidpro   File: test_db.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_clean(self):
        """
        Creates a clean database
        """
        self._log("Generating database...\n")

        try:
            has_data = Org.objects.exists()
        except Exception:  # pragma: no cover
            raise CommandError("Run migrate command first to create database tables")
        if has_data:
            raise CommandError("Can't clean database over non-empty database. Did you mean to use --resume?")

        # this is a new database so clear out redis
        self._log("Clearing out Redis cache... ")
        r = get_redis_connection()
        r.flushdb()
        self._log(self.style.SUCCESS("OK") + "\n")

        superuser = User.objects.create_superuser("root", "root@nyaruka.com", USER_PASSWORD)

        orgs = self.create_orgs(superuser, ORGS, GROUPS, FIELDS, PARTNERS, USER_PASSWORD)
        self.create_contacts(orgs, 100)

        return orgs 
Example 5
Project: DeerU   Author: gojuukaze   File: base.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, stdout=None, stderr=None, no_color=False):
        super().__init__(stdout, stderr, no_color)

        # 检测目录位置
        if self.NEED_PROJECT:
            settings_path = os.path.join(os.getcwd(), 'deeru')
            settings_py = os.path.join(settings_path, 'settings.py')

            if not os.path.exists(settings_py):
                raise CommandError('该命令需要在工程目录下运行')

        self.error = self.stderr.write

        info_out = OutputWrapper(sys.stdout)
        info_out.style_func = self.style.WARNING
        self.info = info_out.write

        success_out = OutputWrapper(sys.stdout)
        success_out.style_func = self.style.SUCCESS
        self.success = success_out.write 
Example 6
Project: zulip   Author: zulip   File: purge_queue.py    License: Apache License 2.0 6 votes vote down vote up
def handle(self, *args: Any, **options: str) -> None:
        def purge_queue(queue_name: str) -> None:
            queue = SimpleQueueClient()
            queue.ensure_queue(queue_name, lambda: None)
            queue.channel.queue_purge(queue_name)

        if options['all']:
            for queue_name in get_active_worker_queues():
                purge_queue(queue_name)
            print("All queues purged")
        elif not options['queue_name']:
            raise CommandError("Missing queue_name argument!")
        else:
            queue_name = options['queue_name']
            if not (queue_name in get_active_worker_queues() or
                    queue_name.startswith("notify_tornado")):
                raise CommandError(f"Unknown queue {queue_name}")

            print(f"Purging queue {queue_name}")
            purge_queue(queue_name)

        print("Done") 
Example 7
Project: django-freeradius   Author: openwisp   File: batch_add_users.py    License: GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        try:
            csvfile = open(options['file'], 'rt')
        except IOError:
            raise CommandError('File does not exist')
        expiration_date = options['expiration']
        if expiration_date:
            expiration_date = datetime.strptime(expiration_date, '%d-%m-%Y')
        batch = self._create_batch(**options)
        batch.expiration_date = expiration_date
        batch.save()
        batch.csvfile.save(csvfile.name.split('/')[-1], File(csvfile))
        csvfile.seek(0)
        try:
            batch.csvfile_upload(csvfile, options['password_length'])
        except ValidationError:
            batch.delete()
            self.stdout.write('Error in uploading users from the file')
            sys.exit(1)
        self.stdout.write('Added a batch of users from a csv file')
        csvfile.close() 
Example 8
Project: django-freeradius   Author: openwisp   File: test_commands.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_batch_add_users_command(self):
        self.assertEqual(self.radius_batch_model.objects.all().count(), 0)
        path = self._get_path('static/test_batch.csv')
        options = dict(file=path, expiration='28-01-2018', name='test')
        self._call_command('batch_add_users', **options)
        self.assertEqual(self.radius_batch_model.objects.all().count(), 1)
        radiusbatch = self.radius_batch_model.objects.first()
        self.assertEqual(get_user_model().objects.all().count(), 3)
        self.assertEqual(radiusbatch.expiration_date.strftime('%d-%m-%y'), '28-01-18')
        path = self._get_path('static/test_batch_new.csv')
        options = dict(file=path, name='test1')
        self._call_command('batch_add_users', **options)
        self.assertEqual(self.radius_batch_model.objects.all().count(), 2)
        self.assertEqual(get_user_model().objects.all().count(), 6)
        invalid_csv_path = self._get_path('static/test_batch_invalid.csv')
        with self.assertRaises(CommandError):
            options = dict(file='doesnotexist.csv', name='test3')
            self._call_command('batch_add_users', **options)
        with self.assertRaises(SystemExit):
            options = dict(file=invalid_csv_path, name='test4')
            self._call_command('batch_add_users', **options) 
Example 9
def handle(self, *args, **options):
        failed = False
        now = datetime.datetime.now(pytz.UTC)
        course_runs = CourseRun.objects.filter(status=CourseRunStatus.Reviewed, go_live_date__lte=now)

        for course_run in course_runs:
            logger.info(_('Publishing course run {key}').format(key=course_run.key))

            try:
                course_run.publish()
            except Exception:  # pylint: disable=broad-except
                logger.exception(_('Failed to publish {key}').format(key=course_run.key))
                failed = True
            else:
                logger.info(_('Successfully published {key}').format(key=course_run.key))

        if failed:
            raise CommandError(_('One or more course runs failed to publish.')) 
Example 10
def test_invalid_args(self):
        partner_code = '--partner={}'.format(self.partner.short_code)
        course_arg = '--course={}'.format(self.course.uuid)

        with self.assertRaises(CommandError) as cm:
            self.call_command(partner_code)  # no courses listed
        self.assertEqual(cm.exception.args[0], 'No courses found. Did you specify an argument?')

        with self.assertRaises(CommandError) as cm:
            self.call_command(course_arg)  # no partner
        self.assertEqual(cm.exception.args[0], 'You must specify --partner')

        with self.assertRaises(CommandError) as cm:
            self.call_command('--partner=NotAPartner', course_arg)
        self.assertEqual(cm.exception.args[0], 'No courses found. Did you specify an argument?')

        with self.assertRaises(CommandError) as cm:
            self.call_command('--allow-for=NotACourseType:audit', partner_code, course_arg)
        self.assertEqual(cm.exception.args[0], 'Supplied Course Type slug [NotACourseType] does not exist.')

        with self.assertRaises(CommandError) as cm:
            self.call_command('--allow-for=verified-audit:NotACourseRunType', partner_code, course_arg)
        self.assertEqual(cm.exception.args[0], 'Supplied Course Run Type slug [NotACourseRunType] does not exist.') 
Example 11
Project: course-discovery   Author: edx   File: api.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def ingest(self):
        attempt_count = 0

        while (attempt_count == 0 or
               (self.processing_failure_occurred and attempt_count < EcommerceApiDataLoader.LOADER_MAX_RETRY)):
            attempt_count += 1
            if self.processing_failure_occurred and attempt_count > 1:  # pragma: no cover
                logger.info('Processing failure occurred attempting {attempt_count} of {max}...'.format(
                    attempt_count=attempt_count,
                    max=EcommerceApiDataLoader.LOADER_MAX_RETRY
                ))

            logger.info('Refreshing ecommerce data from %s...', self.partner.ecommerce_api_url)
            self._load_ecommerce_data()

            if self.processing_failure_occurred:  # pragma: no cover
                logger.warning('Processing failure occurred caused by an exception on at least on of the threads, '
                               'blocking deletes.')
                if attempt_count >= EcommerceApiDataLoader.LOADER_MAX_RETRY:
                    raise CommandError('Max retries exceeded and Ecommerce Data Loader failed to successfully load')
            else:
                self._delete_entitlements() 
Example 12
Project: course-discovery   Author: edx   File: test_api.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_ingest_fails(self, alt_course, alt_currency, alt_mode, product_class, raises):
        """ Verify the proper warnings are logged when data objects are not present. """
        self.mock_courses_api()
        self.mock_products_api(
            alt_course=alt_course,
            alt_currency=alt_currency,
            alt_mode=alt_mode,
            product_class=product_class
        )
        with mock.patch(LOGGER_PATH) as mock_logger:
            if raises:
                with self.assertRaises(CommandError):
                    self.loader.ingest()
            else:
                self.loader.ingest()
            msg = self.compose_warning_log(alt_course, alt_currency, alt_mode, product_class)
            mock_logger.warning.assert_any_call(msg) 
Example 13
def test_missing_required_arguments(self):
        """
        Verify CommandError is raised when required arguments are missing.
        """

        # If a required argument is not specified the system should raise a CommandError
        with self.assertRaises(CommandError):
            call_command(
                "create_sites_and_partners",
                "--dns-name", self.dns_name,
            )

        with self.assertRaises(CommandError):
            call_command(
                "create_sites_and_partners",
                "--theme-path", self.theme_path,
            ) 
Example 14
Project: appstore   Author: nextcloud   File: syncnextcloudreleases.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        oldest_supported = options.get('oldest_supported')
        token = settings.GITHUB_API_TOKEN
        base_url = settings.GITHUB_API_BASE_URL
        client = GitHubClient(base_url, token)

        try:
            releases = get_supported_releases(client, oldest_supported)
        except requests.HTTPError as e:
            raise CommandError('Could not get releases: ' + str(e))

        if options['print']:
            for release in releases:
                self.stdout.write(release)
        else:
            sync_releases(releases) 
Example 15
Project: openwisp-ipam   Author: openwisp   File: test_commands.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_export_subnet_command(self):
        subnet = self._create_subnet(subnet='10.0.0.0/24', name='Sample Subnet')
        self._create_ipaddress(
            ip_address='10.0.0.1', subnet=subnet, description='Testing'
        )
        self._create_ipaddress(
            ip_address='10.0.0.2', subnet=subnet, description='Testing'
        )
        self._create_ipaddress(ip_address='10.0.0.3', subnet=subnet)
        self._create_ipaddress(ip_address='10.0.0.4', subnet=subnet)
        out = StringIO()
        call_command('export_subnet', '10.0.0.0/24', stdout=out)
        self.assertIn('Successfully exported 10.0.0.0/24', out.getvalue())
        with self.assertRaises(CommandError):
            call_command('export_subnet', '11.0.0.0./24')
        with self.assertRaises(CommandError):
            call_command('export_subnet', '11.0.0.0/24') 
Example 16
Project: ocl_web   Author: OpenConceptLab   File: create_org.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def handle(self, *args, **options):

        self.importer.get_args(args, options)

        self.short_name = options['short_name']
        self.full_name = options['full_name']
        self.company_name = options['company_name']
        self.website = options['website']
        self.location = options['location']

        if self.short_name is None and self.importer.filename is None:
            raise CommandError('--short_name or --csv is required.')

        self.importer.connect()

        if self.importer.filename:
            self.handle_file()
        else:
            self.create_org(self.short_name, self.full_name,
                            self.website, self.company_name, self.location) 
Example 17
Project: django-mysql   Author: adamchainz   File: dbparams.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle(self, *args, **options):
        alias = options["alias"]

        try:
            settings_dict = connections[alias].settings_dict
        except ConnectionDoesNotExist:
            raise CommandError("Connection '{}' does not exist".format(alias))

        connection = connections[alias]
        if connection.vendor != "mysql":
            raise CommandError("{} is not a MySQL database connection".format(alias))

        show_mysql = options["mysql"]
        show_dsn = options["dsn"]
        if show_mysql and show_dsn:
            raise CommandError("Pass only one of --mysql and --dsn")
        elif not show_mysql and not show_dsn:
            show_mysql = True

        if show_mysql:
            self.output_for_mysql(settings_dict)
        elif show_dsn:
            self.output_for_dsn(settings_dict) 
Example 18
Project: django-click   Author: GaretJax   File: errcmd.py    License: MIT License 5 votes vote down vote up
def command():
    raise CommandError("Raised error description") 
Example 19
Project: django-click   Author: GaretJax   File: adapter.py    License: MIT License 5 votes vote down vote up
def invoke(self, ctx):
        try:
            return super(DjangoCommandMixin, self).invoke(ctx)
        except CommandError as e:
            # Honor the --traceback flag
            if ctx.traceback:  # NOCOV
                raise
            styled_message = click.style(
                "{}: {}".format(e.__class__.__name__, e), fg="red", bold=True
            )
            click.echo(styled_message, err=True)
            ctx.exit(1) 
Example 20
Project: normandy   Author: mozilla   File: test_commands.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_it_ignores_missing_actions(self, mock_action):
        dont_update_action = ActionFactory(name="dont-update-action", implementation="old")
        mock_action(dont_update_action.name, dont_update_action.arguments_schema, "new")

        with pytest.raises(CommandError):
            call_command("update_actions", "missing-action") 
Example 21
Project: desec-stack   Author: desec-io   File: sync-to-pdns.py    License: MIT License 5 votes vote down vote up
def handle(self, *args, **options):
        domains = Domain.objects.all()

        if options['domain-name']:
            domains = domains.filter(name__in=options['domain-name'])
            domain_names = domains.values_list('name', flat=True)

            for domain_name in options['domain-name']:
                if domain_name not in domain_names:
                    raise CommandError('{} is not a known domain'.format(domain_name))

        catalog_alignment = False
        for domain in domains:
            self.stdout.write('%s ...' % domain.name, ending='')
            try:
                created = self._sync_domain(domain)
                if created:
                    self.stdout.write(f' created (was missing) ...', ending='')
                    catalog_alignment = True
                self.stdout.write(' synced')
            except Exception as e:
                self.stdout.write(' failed')
                msg = 'Error while processing {}: {}'.format(domain.name, e)
                raise CommandError(msg)

        if catalog_alignment:
            call_command('align-catalog-zone') 
Example 22
Project: django-csp-reports   Author: adamalton   File: test_commands.py    License: MIT License 5 votes vote down vote up
def test_invalid(self):
        # Test invalid limit input
        with self.assertRaisesMessage(CommandError, "'JUNK' is not a valid date."):
            call_command('clean_cspreports', 'JUNK') 
Example 23
Project: django-csp-reports   Author: adamalton   File: test_commands.py    License: MIT License 5 votes vote down vote up
def test_invalid_since(self):
        # Test invalid since value
        with self.assertRaisesMessage(CommandError, "'JUNK' is not a valid date."):
            call_command('make_csp_summary', since='JUNK') 
Example 24
Project: django-csp-reports   Author: adamalton   File: test_commands.py    License: MIT License 5 votes vote down vote up
def test_invalid_to(self):
        # Test invalid since to
        with self.assertRaisesMessage(CommandError, "'JUNK' is not a valid date."):
            call_command('make_csp_summary', to='JUNK') 
Example 25
Project: linkedevents   Author: City-of-Helsinki   File: update_n_events.py    License: MIT License 5 votes vote down vote up
def handle(self, model=None, update_all=False, **kwargs):
        if model and model not in ('keyword', 'place'):
            raise CommandError("Model %s not found. Valid models are 'keyword' and 'place'." % (model, ))
        if not model or model == 'keyword':
            self.handle_keywords(update_all=update_all)
        if not model or model == 'place':
            self.handle_places(update_all=update_all) 
Example 26
Project: DeerU   Author: gojuukaze   File: upgrade.py    License: GNU General Public License v3.0 5 votes vote down vote up
def handle(self, *args, **options):
        branch = options['branch']
        subprocess.run('git reset --hard', shell=True)
        result = subprocess.run('git pull origin '+branch, shell=True)
        if result.returncode != 0:
            raise CommandError('\n拉取最新版本失败,请参照手动升级教程升级')
        result =subprocess.run('pip install -r requirements.txt', shell=True)
        if result.returncode != 0:
            raise CommandError('\n安装依赖失败,请参照手动升级教程升级')
        self.success('\n升级完成,运行 python manage.py init_deeru 更新必要配置') 
Example 27
Project: DeerU   Author: gojuukaze   File: install.py    License: GNU General Public License v3.0 5 votes vote down vote up
def install_project(self):
        self.info('开始安装DeerU')

        self.info('下载DeerU ...')

        s = ''
        if os.path.exists(self.name):
            # self.info('已存在相同目录 "%s" ,请选择: d(删除已存在目录); s(跳过下载) ' % self.name)
            s = input('已存在相同目录 "%s" ,请选择: d(删除已存在目录); s(跳过下载): ' % self.name)
            if s == 'd':
                shutil.rmtree(self.name)
            elif s == 's':
                pass
            else:
                raise CommandError('输入错误')

        if s != 's':
            result = subprocess.run('git clone -b %s %s %s' % (self.branch, self.DEERU_GIT_URL, self.name), shell=True)
            if result.returncode != 0:
                raise CommandError('\n下载DeerU失败')

        self.info('安装依赖...')
        result = subprocess.run('pip install -r requirements.txt', cwd=self.name, shell=True)
        if result.returncode != 0:
            raise CommandError('\n安装依赖失败')

        self.info('复制必要文件...')

        context = Context({'SECRET_KEY': get_random_secret_key()}, autoescape=False)

        for template_name, new_file in self.get_project_templates():
            template = Engine().from_string(self.get_template_str(template_name))
            content = template.render(context)
            new_file.write_text(content)

        self.success('\n安装完成 !!') 
Example 28
Project: django-connections   Author: dfunckt   File: runtests.py    License: MIT License 5 votes vote down vote up
def main():
    environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
    
    # setup path
    test_dir = dirname(dirname(abspath(__file__)))
    sys.path.insert(0, test_dir)
    
    try:
        # django >= 1.7
        from django import setup
    except ImportError:
        pass
    else:
        setup()
    
    # setup test env
    from django.test.utils import setup_test_environment
    setup_test_environment()
    
    # setup db
    from django.core.management import call_command, CommandError
    options = {
        'interactive': False,
        'verbosity': 1,
    }
    try:
        call_command('migrate', **options)
    except CommandError:  # Django < 1.7
        call_command('syncdb', **options)
    
    # run tests
    return nose.main() 
Example 29
Project: django-polaris   Author: stellar   File: create_stellar_deposit.py    License: Apache License 2.0 5 votes vote down vote up
def create_stellar_deposit(transaction_id):
        """Create and submit the Stellar transaction for the deposit."""
        try:
            create_stellar_deposit(transaction_id)
        except Exception as e:
            logger.error(e)
            raise CommandError(e) 
Example 30
Project: django-polaris   Author: stellar   File: poll_pending_deposits.py    License: Apache License 2.0 5 votes vote down vote up
def execute_deposits(cls):
        pending_deposits = Transaction.objects.filter(
            kind=Transaction.KIND.deposit,
            status=Transaction.STATUS.pending_user_transfer_start,
        )
        try:
            ready_transactions = rdi.poll_pending_deposits(pending_deposits)
        except NotImplementedError as e:  # pragma: no cover
            # Let the process crash because the anchor needs to implement the
            # integration function.
            raise CommandError(e)
        except Exception:  # pragma: no cover
            # We don't know if poll_pending_deposits() will raise an exception
            # every time its called, but we're going to assume it was a special
            # case and allow the process to continue running by returning instead
            # of re-raising the error. The anchor should see the log messages and
            # fix the issue if it is reoccuring.
            logger.exception("poll_pending_deposits() threw an unexpected exception")
            return
        for transaction in ready_transactions:
            try:
                success = execute_deposit(transaction)
            except ValueError as e:
                logger.error(str(e))
                continue
            if success:
                # Get updated status
                transaction.refresh_from_db()
                try:
                    rdi.after_deposit(transaction)
                except Exception:  # pragma: no cover
                    # Same situation as poll_pending_deposits(), we should assume
                    # this won't happen every time, so we don't stop the loop.
                    logger.exception("after_deposit() threw an unexpected exception")