#35429: Add argparse choices to --database options
-------------------------------------+-------------------------------------
Reporter: Adam | Owner: nobody
Johnson |
Type: | Status: new
Cleanup/optimization |
Component: Core | Version: dev
(Management commands) |
Severity: Normal | Keywords:
Triage Stage: | Has patch: 0
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 1
UI/UX: 0 |
-------------------------------------+-------------------------------------
Many management commands take a `--database` option to select which
database to operate on. Currently, this is unvalidated, causing crashes
when a bad name is typed:
{{{
$ ./manage.py migrate --database deflaut
Traceback (most recent call last):
...
File "/.../django/core/management/commands/migrate.py", line 100, in
handle
self.check(databases=[database])
...
File "/.../django/db/models/fields/__init__.py", line 442, in
_check_backend_specific_checks
errors.extend(connections[alias].validation.check_field(self,
**kwargs))
~~~~~~~~~~~^^^^^^^
File "/.../django/utils/connection.py", line 61, in __getitem__
raise self.exception_class(f"The connection '{alias}' doesn't exist.")
django.utils.connection.ConnectionDoesNotExist: The connection 'deflaut'
doesn't exist.
}}}
We can add [
https://docs.python.org/3.12/library/argparse.html#choices
argparse’s choices] for validation:
{{{
--- django/core/management/commands/migrate.py
+++ django/core/management/commands/migrate.py
@@ -47,6 +47,7 @@ def add_arguments(self, parser):
parser.add_argument(
"--database",
default=DEFAULT_DB_ALIAS,
+ choices=tuple(connections),
help=(
'Nominates a database to synchronize. Defaults to the
"default" '
"database."
}}}
The failure is then graceful, and lists the available options:
{{{
$ ./manage.py migrate --database deflaut
usage: manage.py migrate ...
manage.py migrate: error: argument --database: invalid choice: 'deflaut'
(choose from 'default')
}}}
--
Ticket URL: <
https://code.djangoproject.com/ticket/35429>
Django <
https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.