如何在Django中编写一个自定义管理命令,该命令将URL作为参数?

时间:2022-04-21 08:08:57

I am learning to write custom management commands in Django. I would like to write a command which would take a given URL as a parameter. Something like:

我正在学习在Django中编写自定义管理命令。我想编写一个命令,它将给定的URL作为参数。就像是:

python manage.py command http://example.com

I've read a documentation, but it is not clear to me how to do this. But I can write a command saying 'Hello World!';)

我已经阅读了文档,但我不清楚如何做到这一点。但我可以写一个命令'Hello World!';)

1 个解决方案

#1


12  

try this:

create a file under yourapp/management/commands/yourcommand.py with the following content:

在yourapp / management / commands / yourcommand.py下创建一个文件,其中包含以下内容:

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'A description of your command'

    def add_arguments(self, parser):
        parser.add_argument(
            '--url', dest='url', required=True,
            help='the url to process',
        )

    def handle(self, *args, **options):
        url = options['url']
        # process the url

then you can call your command with

然后你可以用你的命令

python manage.py yourcommand --url http://example.com

and either:

python manage.py --help

or

python manage.py yourcommand --help

will show the description of your command and the argument.

将显示您的命令和参数的描述。

if you don't want to name the argument (the --url part), like in your example, just read the url('s) form args:

如果您不想命名参数(--url部分),就像在您的示例中一样,只需读取url('s)形式的args:

def handle(self, *args, **kwargs):
    for url in args:
        # process the url

hope this helps.

希望这可以帮助。

#1


12  

try this:

create a file under yourapp/management/commands/yourcommand.py with the following content:

在yourapp / management / commands / yourcommand.py下创建一个文件,其中包含以下内容:

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'A description of your command'

    def add_arguments(self, parser):
        parser.add_argument(
            '--url', dest='url', required=True,
            help='the url to process',
        )

    def handle(self, *args, **options):
        url = options['url']
        # process the url

then you can call your command with

然后你可以用你的命令

python manage.py yourcommand --url http://example.com

and either:

python manage.py --help

or

python manage.py yourcommand --help

will show the description of your command and the argument.

将显示您的命令和参数的描述。

if you don't want to name the argument (the --url part), like in your example, just read the url('s) form args:

如果您不想命名参数(--url部分),就像在您的示例中一样,只需读取url('s)形式的args:

def handle(self, *args, **kwargs):
    for url in args:
        # process the url

hope this helps.

希望这可以帮助。