Management Commands
Smarter subclasses Django’s management command framework in order to provide more consistent console output and app logging. SmarterCommand is the base class for all management commands in Smarter, and serves as a drop-in replacement for Django’s base command class.
For more details on the original Django management command interface, see the
django.core.management.base.BaseCommand documentation.
Example
from smarter.lib.django.management.base import SmarterCommand
class Command(SmarterCommand):
help = "My custom management command."
def handle(self, *args, **options):
self.stdout.write(self.style.SUCCESS("Hello from SmarterCommand!"))
- class smarter.lib.django.management.base.SmarterCommand(stdout=None, stderr=None, no_color=False, force_color=False)[source]
Bases:
BaseCommandBase class for custom Django management commands in the Smarter framework.
This class extends Django’s
BaseCommandto provide a standardized interface and additional helper methods for writing robust, user-friendly management commands. It is intended to be subclassed by all custom management commands in the Smarter project.Features:
Standardized output formatting for command start, success, and failure.
Optional display of Django settings at the start of command execution.
Enhanced error handling with clear messaging and exit codes.
Extensible argument parsing via
create_parser.
Parameters:
All parameters accepted by Django’s
BaseCommandare supported.Command-Line Options:
--settings_output(bool): If specified, outputs Django settings at the beginning of the command’s console output.
Methods:
handle_begin(): Prints a formatted header indicating the start of the command.handle_completed_success(msg: Optional[str] = None): Prints a formatted success message. Ifmsgis provided, it is displayed; otherwise, a default message is shown.handle_completed_failure(err: Optional[Exception] = None, msg: Optional[str] = None): Prints a formatted error message. Iferris provided, the error details are included and the process exits with code 1.create_parser(prog_name, subcommand, **kwargs): Extends the default argument parser to include the--settings_outputoption.handle(*args, **options): Abstract method to be implemented by subclasses. Contains the main logic for the command.
Example Usage:
from smarter.lib.django.management.base import SmarterCommand class MyCommand(SmarterCommand): help = "My custom command." def handle(self, *args, **options): self.handle_begin() # Command logic here self.handle_completed_success("MyCommand finished successfully.")
Notes:
Subclasses must implement the
handlemethod.Use the provided helper methods to ensure consistent output and error handling.
Warning:
If
handle_completed_failureis called with an exception, the process will exit with code 1.Do not override
__init__unless necessary; always callsuper().__init__.
- create_parser(prog_name, subcommand, **kwargs)[source]
Create and return the
ArgumentParserwhich will be used to parse the arguments to this command.It adds the
--settings_outputflag to Django’s parser.- Parameters:
prog_name – The program name, e.g.
manage.py.subcommand – The command’s name.
kwargs – Passed to Django’s
create_parser().
- Returns:
The parser.
- execute(*args, **options)[source]
Run the command, and keep count of the SmarterCommands that are running in this thread.
The count is what
is_nested()reads. It is decremented however the command ends.- Parameters:
args – Passed to Django’s
BaseCommand.execute().options – Passed to Django’s
BaseCommand.execute().
- Returns:
Whatever Django’s
BaseCommand.execute()returns.
- handle(*args, **options)[source]
Run the command’s logic, which every subclass implements.
- Parameters:
args – The command’s positional arguments.
options – The command’s parsed options.
- Raises:
NotImplementedError – always, in this base class.
- handle_begin()[source]
Log the command’s start, as a banner.
A command that another command called logs one DEBUG line instead: an init job runs hundreds of
apply_manifestcommands, and their banners would be most of its log.
- handle_completed_failure(err=None, msg=None)[source]
Log that the command failed, and exit with status 1 if there was an error.
The stack trace of the exception being handled is logged too, when
erris given.- Parameters:
- Raises:
SystemExit – With status 1, when
erris given.
- property is_nested: bool
Whether another SmarterCommand called this one, e.g. with
call_command().- Returns:
True when this command runs inside another SmarterCommand.
- run_from_argv(argv)[source]
Run the command from the command line, and report an unexpected error without a stack trace.
Django already prints a
CommandErroras one line, and exits with status 1. Any other exception would print a stack trace, which is no way to tell an operator what went wrong. This prints the exception’s type and message instead, logs the stack trace at DEBUG, and exits with status 1.--tracebackrestores Django’s behavior, for debugging. Only the command line is affected:call_command()still raises.- Parameters:
argv – The command line, e.g.
["manage.py", "create_user", "--username", "jdoe"].- Raises:
SystemExit – With status 1, after an unexpected error.
Example resources
The platform’s example resources are not in its source tree. Their manifests live in GitHub
repositories of their own, the example manifests repository and the Stackademy example project, and manage.py load_from_github applies them:
it resolves the owner, applies each manifest in a transaction, in the order of their kinds’
dependencies, fills in manifest templates, and reports the manifests that failed without stopping
the others. manage.py initialize_platform runs it for both repositories. See
load_from_github.