本文整理汇总了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
示例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)
示例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)
))
示例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
示例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
示例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")
示例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()
示例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)
示例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.'))
示例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.')
示例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()
示例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)
示例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,
)
示例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)
示例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')