【command】djangoでコマンドを自作してみる

2021年6月30日

参考

階層

階層は下の通りです。

.
└── django_project
    ├── manage.py
    └── myapp
        └── management
            └── commands
                └── sample_command.py

プログラム

sample_command.py と説明は下の通りです。

# django_project/myapp/management/commands/sample_command.py
from django.core.management.base import BaseCommand
class Command(BaseCommand):
    """
    python manage.py help sample_command で表示される説明を指定する。
    """
    help = 'explanation'
    def add_arguments(self, parser):
        """
        python manage.py sample_command hello_world と実行した時、
        hello_world を options['sample_arg'] に格納する。
        """
        parser.add_argument('sample_arg')
    def handle(self, *args, **options):
        """
        options['sample_arg']に格納されている hello_world を出力する。
        """
        print(options['sample_arg'])

実行と実行結果

python manage.py sample_command hello_world
hello_world

その他

【- -】

[- -]を付けるとオプションに出来るみたいですね。
オプションの後に引数を指定できます。

...
    def add_arguments(self, parser):
        parser.add_argument('--check')
    def handle(self, *args, **options):
        print(options['check'])
...
# 実行:python manage.py sample_command --check aiueo
# 結果:aiueo

【action='store_true'】

store_true を指定するとオプションがあるときに true が格納されるみたいですね。
store_false を指定すると下の結果は逆になります。

...
    def add_arguments(self, parser):
        parser.add_argument('--check', action='store_true') 
    def handle(self, *args, **options):
        print(options['check'])
...
# 実行:python manage.py sample_command --check
# 結果:True
# 実行:python manage.py sample_command
# 結果:False

【default=】

オプションに引数がない場合の引数のデフォルト値を設定できるみたいですね。
引数を指定すると上書きされます。

...
    def add_arguments(self, parser):
        parser.add_argument('--check', default='default_value') 
    def handle(self, *args, **options):
        print(options['check'])
...
# 実行:python manage.py sample_command
# 結果:default_value
# 実行:python manage.py sample_command --check aiueo
# 結果:aiueo

【dest=】

['オプション名']で値を取得していましたが、オプション名以外を指定する時は dest で指定するみたいですね。

...
    def add_arguments(self, parser):
        parser.add_argument('--check', dest='this')
    def handle(self, *args, **options):
        print(options['this'])
...
# 実行:python manage.py sample_command --check aiueo
# 結果:aiueo
YouTube

2021年6月30日