Skip to content

Instantly share code, notes, and snippets.

@mloza
Last active April 14, 2020 19:54
Show Gist options
  • Save mloza/b73d9459d30a46986f2cb88effc30124 to your computer and use it in GitHub Desktop.
Save mloza/b73d9459d30a46986f2cb88effc30124 to your computer and use it in GitHub Desktop.
Kod źródłowy do postu na temat dodawania nowych poleceń w Django i manage.py znajdujący się pod adresem https://blog.mloza.pl/django-dodawanie-obslugi-nowych-komend-przez-manage-py
def add_arguments(self, parser):
parser.add_argument('-d', '--display',
action='store_true',
default=False,
dest='show',
help='display text')
from django.core.management import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
self.stdout.write("Basic command")
from django.core.management import BaseCommand
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("-r", "--repeat", help="how many times repeat text", default=1, type=int)
parser.add_argument('-d', '--display',
action='store_true',
dest='show',
default=False,
help='display text')
def handle(self, *args, **options):
self.stdout.write("Basic command")
if options['show']:
for i in range(0, options['repeat']):
self.stdout.write("Optional text")
def handle(self, *args, **options):
print("Basic command")
if options['show']:
self.stdout.write("Optional text")
def handle(self, *args, **options):
print("Basic command")
if options['show']:
for i in range(0, options['repeat']):
self.stdout.write("Optional text")
from django.core.management import call_command
from django.test import TestCase
from django.utils.six import StringIO
class BlogCommandTest(TestCase):
def test_basic_command_output(self):
out = StringIO()
call_command('blog', stdout=out)
self.assertIn('Basic command\n', out.getvalue())
def test_command_with_display_parameter(self):
out = StringIO()
call_command('blog', '--display', stdout=out)
self.assertEquals('Basic command\nOptional text\n', out.getvalue())
def test_command_with_display_and_repeatparameter(self):
out = StringIO()
call_command('blog', '--display', '-r 3', stdout=out)
self.assertEquals('Basic command\nOptional text\nOptional text\nOptional text\n', out.getvalue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment