当前位置: 首页>>代码示例>>Python>>正文


Python management.CommandError方法代码示例

本文整理汇总了Python中django.core.management.CommandError方法的典型用法代码示例。如果您正苦于以下问题:Python management.CommandError方法的具体用法?Python management.CommandError怎么用?Python management.CommandError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.core.management的用法示例。


在下文中一共展示了management.CommandError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: handle_app_config

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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 
开发者ID:BetterWorks,项目名称:django-anonymizer,代码行数:24,代码来源:check_anonymizers.py

示例2: handle

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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) 
开发者ID:desec-io,项目名称:desec-stack,代码行数:22,代码来源:sync-from-pdns.py

示例3: authenticate

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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)
                )) 
开发者ID:City-of-Helsinki,项目名称:linkedevents,代码行数:20,代码来源:city_sdk.py

示例4: create_clean

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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 
开发者ID:rapidpro,项目名称:casepro,代码行数:27,代码来源:test_db.py

示例5: __init__

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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 
开发者ID:gojuukaze,项目名称:DeerU,代码行数:22,代码来源:base.py

示例6: handle

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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") 
开发者ID:zulip,项目名称:zulip,代码行数:24,代码来源:purge_queue.py

示例7: handle

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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() 
开发者ID:openwisp,项目名称:django-freeradius,代码行数:23,代码来源:batch_add_users.py

示例8: test_batch_add_users_command

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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) 
开发者ID:openwisp,项目名称:django-freeradius,代码行数:23,代码来源:test_commands.py

示例9: handle

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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.')) 
开发者ID:edx,项目名称:course-discovery,代码行数:20,代码来源:publish_live_course_runs.py

示例10: test_invalid_args

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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.') 
开发者ID:edx,项目名称:course-discovery,代码行数:25,代码来源:test_backpopulate_course_type.py

示例11: ingest

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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() 
开发者ID:edx,项目名称:course-discovery,代码行数:24,代码来源:api.py

示例12: test_ingest_fails

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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) 
开发者ID:edx,项目名称:course-discovery,代码行数:19,代码来源:test_api.py

示例13: test_missing_required_arguments

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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,
            ) 
开发者ID:edx,项目名称:course-discovery,代码行数:19,代码来源:test_create_sites_and_partners.py

示例14: handle

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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) 
开发者ID:nextcloud,项目名称:appstore,代码行数:18,代码来源:syncnextcloudreleases.py

示例15: test_export_subnet_command

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import CommandError [as 别名]
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') 
开发者ID:openwisp,项目名称:openwisp-ipam,代码行数:19,代码来源:test_commands.py


注:本文中的django.core.management.CommandError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。