django

[Django] manage.py 명령어 Customize

sklass 2021. 9. 10. 23:46

Djanog 를 실행시킬때 manage.py 뒤에 오는 명령어들은 흔히 runserver 나 test등을 꼽을 수 있습니다. runserver는 django의 웹서버를 활성화 시켜서 로컬 환경에서 테스트를 용이하게끔 하는것이고, test는 TestCase들이 있다면 테스트할 수 있는 명령어입니다. 이외에도 django를 쓰다보면, 특별한 기능을 명령어를 실행시켜서 만들고 싶을때가 있습니다. 예를 들어서 테스트를 할때 뒤에 --tag 명령어가 너무 많이 붙는다던지, option이 길어져서 이거를 하나의 명령어를 실행시키고 그 명령어가 os.system()으로 길고 복잡한 명령어를 실행시키게끔 할 수도 있습니다.

이를 위해서는 아래와 같이 애플리케이션에 management/commands 디렉토리를 추가하면 됩니다. 

polls/
    __init__.py
    models.py
    management/
        __init__.py
        commands/
            __init__.py
            _private.py
            closepoll.py
    tests.py
    views.py

그리고 polls/management/commands/closepoll.py 를 아래와 같이 편집합니다.

from django.core.management.base import BaseCommand, CommandError
from polls.models import Question as Poll

class Command(BaseCommand):
    help = 'Closes the specified poll for voting'

    def add_arguments(self, parser):
        parser.add_argument('poll_ids', nargs='+', type=int)

    def handle(self, *args, **options):
        for poll_id in options['poll_ids']:
            try:
                poll = Poll.objects.get(pk=poll_id)
            except Poll.DoesNotExist:
                raise CommandError('Poll "%s" does not exist' % poll_id)

            poll.opened = False
            poll.save()

            self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))

이로 인해 새로운 커스텀 커맨드인 closepoll을 아래와 같이 실행시킬 수 있습니다.

$ python3 manage.py closepoll 1.