Python django.core.management.base.CommandError() Examples
The following are 30
code examples of django.core.management.base.CommandError().
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 also want to check out all available functions/classes of the module
django.core.management.base
, or try the search function
.
Example #1
Source File: run_gunicorn.py From jbox with MIT License | 6 votes |
def handle(self, addrport=None, *args, **options): # deprecation warning to announce future deletion in R21 util.warn("""This command is deprecated. You should now run your application with the WSGI interface installed with your project. Ex.: gunicorn myproject.wsgi:application See https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/gunicorn/ for more info.""") if args: raise CommandError('Usage is run_gunicorn %s' % self.args) if addrport: sys.argv = sys.argv[:-1] options['bind'] = addrport admin_media_path = options.pop('admin_media_path', '') DjangoApplicationCommand(options, admin_media_path).run()
Example #2
Source File: populate.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
def handle(self, *args, **options): print('Populate Genes!') populate_genes() print('Populate Diseases from OMIM!') populate_diseases() #populate diseases from OMIM print('Populate Diseases from CGD!') populate_CGD() #populate dieases from CGD #populate dieases from CGD # for poll_id in args: # try: # poll = Poll.objects.get(pk=int(poll_id)) # except Poll.DoesNotExist: # raise CommandError('Poll "%s" does not exist' % poll_id) # poll.opened = False # poll.save() # self.stdout.write('Successfully closed poll "%s"' % poll_id)
Example #3
Source File: populate.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
def handle(self, *args, **options): print('Populate Genes!') populate_genes() print('Populate Diseases from OMIM!') populate_diseases() #populate diseases from OMIM print('Populate Diseases from CGD!') populate_CGD() #populate dieases from CGD #populate dieases from CGD # for poll_id in args: # try: # poll = Poll.objects.get(pk=int(poll_id)) # except Poll.DoesNotExist: # raise CommandError('Poll "%s" does not exist' % poll_id) # poll.opened = False # poll.save() # self.stdout.write('Successfully closed poll "%s"' % poll_id)
Example #4
Source File: lift_variant_to_hg38_2_3_tests.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
def test_command(self, mock_single_es_variants, mock_logger, mock_input): # Test user did not confirm. mock_input.return_value = 'n' with self.assertRaises(CommandError) as ce: call_command('lift_variant_to_hg38', SAVED_VARIANT_GUID, VARIANT_ID) self.assertEqual(str(ce.exception), 'Error: user did not confirm') # Test user did confirm. mock_single_es_variants.return_value = PARSED_VARIANTS[0] mock_input.return_value = 'y' call_command('lift_variant_to_hg38', SAVED_VARIANT_GUID, VARIANT_ID) mock_logger.info.assert_called_with('---Done---') saved_variant = SavedVariant.objects.get(guid = SAVED_VARIANT_GUID) mock_single_es_variants.assert_called_with([saved_variant.family], VARIANT_ID, return_all_queried_families = True) self.assertListEqual( [PARSED_VARIANTS[0]['xpos'], PARSED_VARIANTS[0]['ref'], PARSED_VARIANTS[0]['alt'], PARSED_VARIANTS[0]], [saved_variant.xpos_start, saved_variant.ref, saved_variant.alt, saved_variant.saved_variant_json])
Example #5
Source File: test_catalog_command.py From ideascube with GNU Affero General Public License v3.0 | 6 votes |
def test_upgrade_unavailable_package(tmpdir, settings, staticsite_path): remote_catalog_file = tmpdir.join('source').join('catalog.yml') remote_catalog_file.write_text('all: {}', 'utf-8') call_command( 'catalog', 'remotes', 'add', 'foo', 'Content from Foo', 'file://{}'.format(remote_catalog_file.strpath)) call_command('catalog', 'cache', 'update') install_dir = Path(settings.CATALOG_NGINX_INSTALL_DIR) assert install_dir.join('the-site').check(exists=False) with pytest.raises(CommandError) as excinfo: call_command('catalog', 'upgrade', 'the-site') assert 'No such package: the-site' in excinfo.exconly() assert install_dir.join('the-site').check(exists=False)
Example #6
Source File: add_project_tag_2_3_tests.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
def test_missing_required_args(self): out = StringIO() with self.assertRaises(CommandError) as err: call_command('add_project_tag', stdout = out) self.assertIn(str(err.exception), ['Error: argument --project is required', 'Error: the following arguments are required: --project, --name, --order']) with self.assertRaises(CommandError) as err: call_command('add_project_tag', '--project={}'.format(TAG_ARGUMENTS["project"]), stdout = out) self.assertIn(str(err.exception), ['Error: argument --name is required', 'Error: the following arguments are required: --name, --order']) with self.assertRaises(CommandError) as err: call_command('add_project_tag', '--project={}'.format(TAG_ARGUMENTS["project"]), '--name={}'.format(TAG_ARGUMENTS["name"]), stdout = out) self.assertIn(str(err.exception), ['Error: argument --order is required', 'Error: the following arguments are required: --order'])
Example #7
Source File: collecttools.py From resolwe with Apache License 2.0 | 6 votes |
def get_confirmation(self): """Get user confirmation to proceed.""" if self.clear: action = "This will DELETE ALL FILES in this location!" else: action = "This will overwrite existing files!" message = ( "\n" "You have requested to collect static files at the destination\n" "location as specified in your settings\n" "\n" " {destination}\n" "\n" "{action}\n" "Are you sure you want to do this?\n" "\n" "Type 'yes' to continue, or 'no' to cancel: ".format( destination=self.destination_path, action=action, ) ) if input("".join(message)) != "yes": raise CommandError("Collecting tools cancelled.")
Example #8
Source File: lift_project_to_hg38_2_3_tests.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
def test_command_error_missing_families(self, mock_get_es_samples, mock_logger): mock_get_es_samples.return_value = ['HG00731', 'HG00732', 'HG00733'], INDEX_METADATA with self.assertRaises(CommandError) as ce: call_command('lift_project_to_hg38', '--project={}'.format(PROJECT_NAME), '--es-index={}'.format(ELASTICSEARCH_INDEX)) self.assertEqual(str(ce.exception), 'The following families have saved variants but are missing from the callset: 1.') calls = [ mock.call('Updating project genome version for {}'.format(PROJECT_NAME)), mock.call('Validating es index test_index'), ] mock_logger.info.assert_has_calls(calls) mock_get_es_samples.assert_called_with(ELASTICSEARCH_INDEX)
Example #9
Source File: lift_project_to_hg38_2_3_tests.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
def test_command_error_unmatched_sample(self, mock_get_es_samples, mock_logger): mock_get_es_samples.return_value = ['ID_NOT_EXIST'], INDEX_METADATA with self.assertRaises(CommandError) as ce: call_command('lift_project_to_hg38', '--project={}'.format(PROJECT_NAME), '--es-index={}'.format(ELASTICSEARCH_INDEX)) self.assertEqual(str(ce.exception), 'Matches not found for ES sample ids: ID_NOT_EXIST.') calls = [ mock.call('Updating project genome version for {}'.format(PROJECT_NAME)), mock.call('Validating es index test_index') ] mock_logger.info.assert_has_calls(calls) mock_get_es_samples.assert_called_with(ELASTICSEARCH_INDEX)
Example #10
Source File: populate.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
def handle(self, *args, **options): print('Populate Genes!') populate_genes() print('Populate Diseases from OMIM!') populate_diseases() #populate diseases from OMIM print('Populate Diseases from CGD!') populate_CGD() #populate dieases from CGD #populate dieases from CGD # for poll_id in args: # try: # poll = Poll.objects.get(pk=int(poll_id)) # except Poll.DoesNotExist: # raise CommandError('Poll "%s" does not exist' % poll_id) # poll.opened = False # poll.save() # self.stdout.write('Successfully closed poll "%s"' % poll_id)
Example #11
Source File: lift_variant_to_hg38.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
def handle(self, *args, **options): """transfer project""" saved_variant_guid = options['saved_variant_guid'] variant_id = options['variant_id'] saved_variant = SavedVariant.objects.get(guid=saved_variant_guid) if input('Are you sure you want to update {}-{}-{} to {} (y/n)? '.format( saved_variant.xpos_start, saved_variant.ref, saved_variant.alt, variant_id)) != 'y': raise CommandError('Error: user did not confirm') es_variant = get_single_es_variant([saved_variant.family], variant_id, return_all_queried_families=True) saved_variant.xpos_start = es_variant['xpos'] saved_variant.ref = es_variant['ref'] saved_variant.alt = es_variant['alt'] saved_variant.saved_variant_json = es_variant saved_variant.save() logger.info('---Done---')
Example #12
Source File: makemessages.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def gettext_popen_wrapper(args, os_err_exc_type=CommandError, stdout_encoding="utf-8"): """ Makes sure text obtained from stdout of gettext utilities is Unicode. """ # This both decodes utf-8 and cleans line endings. Simply using # popen_wrapper(universal_newlines=True) doesn't properly handle the # encoding. This goes back to popen's flaky support for encoding: # https://bugs.python.org/issue6135. This is a solution for #23271, #21928. # No need to do anything on Python 2 because it's already a byte-string there. manual_io_wrapper = six.PY3 and stdout_encoding != DEFAULT_LOCALE_ENCODING stdout, stderr, status_code = popen_wrapper(args, os_err_exc_type=os_err_exc_type, universal_newlines=not manual_io_wrapper) if manual_io_wrapper: stdout = io.TextIOWrapper(io.BytesIO(stdout), encoding=stdout_encoding).read() if six.PY2: stdout = stdout.decode(stdout_encoding) return stdout, stderr, status_code
Example #13
Source File: setname.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def handle(self, *args, **options): """Handle the command invocation.""" site_id = getattr(settings, 'SITE_ID', None) site_name = getattr(settings, 'SITE_NAME', None) site_domain = getattr(settings, 'SITE_DOMAIN', None) if not site_id: raise CommandError('No SITE_ID specified in project settings') if not site_name: raise CommandError('No SITE_NAME specified in project settings') if not site_domain: raise CommandError('No SITE_DOMAIN specified in project settings') try: site = Site.objects.get(pk=site_id) except Site.DoesNotExist: # pylint: disable=no-member raise CommandError('Site "%s" does not exist' % site_id) site.name = site_name site.domain = site_domain site.save() msg = 'Successfully configured site #%s; name: "%s"; domain: %s' % (site_id, site_name, site_domain) self.stdout.write(self.style.SUCCESS(msg)) # pylint: disable=no-member
Example #14
Source File: senddigest.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def handle(self, *args, **options): """Handle the command invocation.""" if options['frequency'] == 'daily': self.report(send_digest_emails(DigestFrequency.daily)) elif options['frequency'] == 'weekly': digest_day = getattr(settings, 'DIGEST_WEEKLY_DAY') current_day = timezone.now().weekday() if current_day == digest_day or options['force']: if current_day != digest_day and options['force']: msg = 'Forcing weekly digest to be sent (scheduled=%s, current=%s)' % (digest_day, current_day) self.stdout.write(self.style.WARNING(msg)) # pylint: disable=no-member self.report(send_digest_emails(DigestFrequency.weekly)) else: msg = 'Skipping weekly digest until day %s (current=%s)' % (digest_day, current_day) self.stdout.write(self.style.WARNING(msg)) # pylint: disable=no-member else: raise CommandError('Expected frequency "daily" or "weekly"')
Example #15
Source File: createadmin.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def handle(self, *args, **options): """Handle the command invocation.""" email = getattr(settings, 'ADMIN_EMAIL_ADDRESS', None) username = getattr(settings, 'ADMIN_USERNAME', None) password = getattr(settings, 'ADMIN_PASSWORD', None) if not email or not username or not password: raise CommandError('ADMIN_USERNAME, ADMIN_PASSWORD, and ADMIN_EMAIL_ADDRESS must be set') admin = User(username=username, email=email) admin.set_password(password) admin.is_superuser = True admin.is_staff = True admin.save() msg = 'Successfully configured admin %s (%s)' % (username, email) self.stdout.write(self.style.SUCCESS(msg)) # pylint: disable=no-member
Example #16
Source File: startproject.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def handle(self, **options): project_name, target = options.pop('name'), options.pop('directory') self.validate_name(project_name, "project") # Check that the project_name cannot be imported. try: import_module(project_name) except ImportError: pass else: raise CommandError("%r conflicts with the name of an existing " "Python module and cannot be used as a " "project name. Please try another name." % project_name) # Create a random SECRET_KEY to put it in the main settings. chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' options['secret_key'] = get_random_string(50, chars) super(Command, self).handle('project', project_name, target, **options)
Example #17
Source File: test_catalog_command.py From ideascube with GNU Affero General Public License v3.0 | 6 votes |
def test_install_unavailable_package(tmpdir, settings, staticsite_path): remote_catalog_file = tmpdir.join('source').join('catalog.yml') remote_catalog_file.write_text('all: {}', 'utf-8') call_command( 'catalog', 'remotes', 'add', 'foo', 'Content from Foo', 'file://{}'.format(remote_catalog_file.strpath)) call_command('catalog', 'cache', 'update') install_dir = Path(settings.CATALOG_NGINX_INSTALL_DIR) assert install_dir.join('the-site').check(exists=False) with pytest.raises(CommandError) as excinfo: call_command('catalog', 'install', 'the-site') assert 'No such package: the-site' in excinfo.exconly() assert install_dir.join('the-site').check(exists=False)
Example #18
Source File: collectstatic.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def link_file(self, path, prefixed_path, source_storage): """ Attempt to link ``path`` """ # Skip this file if it was already copied earlier if prefixed_path in self.symlinked_files: return self.log("Skipping '%s' (already linked earlier)" % path) # Delete the target file if needed or break if not self.delete_file(path, prefixed_path, source_storage): return # The full path of the source file source_path = source_storage.path(path) # Finally link the file if self.dry_run: self.log("Pretending to link '%s'" % source_path, level=1) else: self.log("Linking '%s'" % source_path, level=1) full_path = self.storage.path(prefixed_path) try: os.makedirs(os.path.dirname(full_path)) except OSError: pass try: if os.path.lexists(full_path): os.unlink(full_path) os.symlink(source_path, full_path) except AttributeError: import platform raise CommandError("Symlinking is not supported by Python %s." % platform.python_version()) except NotImplementedError: import platform raise CommandError("Symlinking is not supported in this " "platform (%s)." % platform.platform()) except OSError as e: raise CommandError(e) if prefixed_path not in self.symlinked_files: self.symlinked_files.append(prefixed_path)
Example #19
Source File: test_runner.py From resolwe with Apache License 2.0 | 5 votes |
def _git(self, *args): """Helper to run Git command.""" try: return subprocess.check_output(["git"] + list(args)).decode("utf8").strip() except subprocess.CalledProcessError: raise CommandError("Git command failed.")
Example #20
Source File: changepassword.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def _get_pass(self, prompt="Password: "): p = getpass.getpass(prompt=force_str(prompt)) if not p: raise CommandError("aborted") return p
Example #21
Source File: dbshell.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def handle(self, **options): connection = connections[options.get('database')] try: connection.client.runshell() except OSError: # Note that we're assuming OSError means that the client program # isn't installed. There's a possibility OSError would be raised # for some other reason, in which case this error message would be # inaccurate. Still, this message catches the common case. raise CommandError('You appear not to have the %r program installed or on your path.' % connection.client.executable_name)
Example #22
Source File: runserver.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def handle(self, *args, **options): from django.conf import settings if not settings.DEBUG and not settings.ALLOWED_HOSTS: raise CommandError('You must set settings.ALLOWED_HOSTS if DEBUG is False.') self.use_ipv6 = options.get('use_ipv6') if self.use_ipv6 and not socket.has_ipv6: raise CommandError('Your Python does not support IPv6.') self._raw_ipv6 = False if not options.get('addrport'): self.addr = '' self.port = DEFAULT_PORT else: m = re.match(naiveip_re, options['addrport']) if m is None: raise CommandError('"%s" is not a valid port number ' 'or address:port pair.' % options['addrport']) self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups() if not self.port.isdigit(): raise CommandError("%r is not a valid port number." % self.port) if self.addr: if _ipv6: self.addr = self.addr[1:-1] self.use_ipv6 = True self._raw_ipv6 = True elif self.use_ipv6 and not _fqdn: raise CommandError('"%s" is not a valid IPv6 address.' % self.addr) if not self.addr: self.addr = '::1' if self.use_ipv6 else '127.0.0.1' self._raw_ipv6 = bool(self.use_ipv6) self.run(**options)
Example #23
Source File: compilemessages.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def compile_messages(self, locations): """ Locations is a list of tuples: [(directory, file), ...] """ for i, (dirpath, f) in enumerate(locations): if self.verbosity > 0: self.stdout.write('processing file %s in %s\n' % (f, dirpath)) po_path = os.path.join(dirpath, f) if has_bom(po_path): raise CommandError("The %s file has a BOM (Byte Order Mark). " "Django only supports .po files encoded in " "UTF-8 and without any BOM." % po_path) base_path = os.path.splitext(po_path)[0] # Check writability on first location if i == 0 and not is_writable(npath(base_path + '.mo')): self.stderr.write("The po files under %s are in a seemingly not writable location. " "mo files will not be updated/created." % dirpath) return args = [self.program] + self.program_options + ['-o', npath(base_path + '.mo'), npath(base_path + '.po')] output, errors, status = popen_wrapper(args) if status: if errors: msg = "Execution of %s failed: %s" % (self.program, errors) else: msg = "Execution of %s failed" % self.program raise CommandError(msg)
Example #24
Source File: loaddata.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def parse_name(self, fixture_name): """ Splits fixture name in name, serialization format, compression format. """ parts = fixture_name.rsplit('.', 2) if len(parts) > 1 and parts[-1] in self.compression_formats: cmp_fmt = parts[-1] parts = parts[:-1] else: cmp_fmt = None if len(parts) > 1: if parts[-1] in self.serialization_formats: ser_fmt = parts[-1] parts = parts[:-1] else: raise CommandError( "Problem installing fixture '%s': %s is not a known " "serialization format." % (''.join(parts[:-1]), parts[-1])) else: ser_fmt = None name = '.'.join(parts) return name, ser_fmt, cmp_fmt
Example #25
Source File: badgify_sync.py From django-badgify with MIT License | 5 votes |
def handle_label(self, label, **options): """ Command handler. """ if not hasattr(commands, 'sync_%s' % label): raise CommandError('"%s" is not a valid command.' % label) getattr(commands, 'sync_%s' % label)(**sanitize_command_options(options))
Example #26
Source File: test_command_config.py From ideascube with GNU Affero General Public License v3.0 | 5 votes |
def test_reset_invalid_key(capsys, monkeypatch): monkeypatch.setattr( 'ideascube.configuration.registry.REGISTRY', {'namespace1': {}}) with pytest.raises(CommandError) as exc_info: call_command('config', 'reset', 'namespace1', 'key1') assert ( 'Unknown configuration key: "namespace1.key1"') in str(exc_info.value)
Example #27
Source File: collecttools.py From resolwe with Apache License 2.0 | 5 votes |
def __init__(self, *args, **kwargs): """Initialize command.""" super().__init__(*args, **kwargs) self.interactive = None self.clear = None if not hasattr(settings, "FLOW_TOOLS_ROOT"): raise CommandError("FLOW_TOOLS_ROOT must be defined in Django settings.") self.destination_path = settings.FLOW_TOOLS_ROOT
Example #28
Source File: test_command_config.py From ideascube with GNU Affero General Public License v3.0 | 5 votes |
def test_set_invalid_config(monkeypatch): monkeypatch.setattr( 'ideascube.configuration.registry.REGISTRY', {'namespace1': {'key1': {'type': int, 'default': 0}}}) with pytest.raises(CommandError) as exc_info: call_command('config', 'set', 'namespace1', 'key1', "'value 1'") assert ( 'Invalid type for configuration key "namespace1.key1": expected ' "<class 'int'>, got <class 'str'>") in str(exc_info.value)
Example #29
Source File: test_command_config.py From ideascube with GNU Affero General Public License v3.0 | 5 votes |
def test_set_config_no_namespace(monkeypatch): monkeypatch.setattr('ideascube.configuration.registry.REGISTRY', {}) with pytest.raises(CommandError) as exc_info: call_command('config', 'set', 'namespace1', 'key1', "'value 1'") assert ( 'Unknown configuration namespace: "namespace1"') in str(exc_info.value)
Example #30
Source File: test_command_config.py From ideascube with GNU Affero General Public License v3.0 | 5 votes |
def test_list_keys_invalid_namespace(capsys, monkeypatch): monkeypatch.setattr('ideascube.configuration.registry.REGISTRY', {}) with pytest.raises(CommandError) as exc_info: call_command('config', 'list', 'namespace1') assert ( 'Unknown configuration namespace: "namespace1"') in str(exc_info.value)