【问题标题】:How to write in Django a custom management command which takes a URL as a parameter?如何在 Django 中编写以 URL 作为参数的自定义管理命令?
【发布时间】:2017-11-25 19:16:36
【问题描述】:

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

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

我已阅读文档,但我不清楚如何执行此操作。 但是我可以写一个命令说'Hello World!';)

【问题讨论】:

    标签: python django command


    【解决方案1】:

    试试这个:

    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
    

    然后你可以调用你的命令

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

    或者:

    python manage.py --help
    

    python manage.py yourcommand --help
    

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

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

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

    希望这会有所帮助。

    【讨论】:

    • 很好的例子。但问题只涉及一个 URL。所以把'--'放在add_argument前面,它会神奇地工作(好吧,感谢argparse)。
    • 谢谢!这很有帮助!但我不明白最后一部分(没有 --url) - 之后应该是什么:for url in args:
    • @AlekSZ,这取决于你,在那里你处理作为参数给出的 URL。
    • 完美解释
    猜你喜欢
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2019-06-08
    • 2016-03-28
    • 1970-01-01
    • 2018-06-19
    相关资源
    最近更新 更多