gpt4 book ai didi

python - 向自定义 Django management/manage.py 命令添加确认步骤

转载 作者:太空狗 更新时间:2023-10-29 22:21:24 26 4
gpt4 key购买 nike

我在 this tutorial 之后创建了以下自定义管理命令.

from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User

from topspots.models import Notification


class Command(BaseCommand):
help = 'Sends message to all users'

def add_arguments(self, parser):
parser.add_argument('message', nargs='?')

def handle(self, *args, **options):
message = options['message']
users = User.objects.all()
for user in users:
Notification.objects.create(message=message, recipient=user)

self.stdout.write(
self.style.SUCCESS(
'Message:\n\n%s\n\nsent to %d users' % (message, len(users))
)
)

它完全按照我的意愿工作,但我想添加一个确认步骤,以便在 for user in users: 循环之前询问您是否真的要将消息 X 发送到N 个用户,如果选择“否”则命令中止。

我认为这很容易完成,因为它发生在一些内置管理命令中,但它似乎没有在教程中涵盖这一点,甚至在搜索和查看内置管理命令的源代码之后管理命令,我无法自己弄清楚。

最佳答案

您可以使用 Python 的 raw_input/input 函数。这是 Django 的 source code 中的示例方法:

from django.utils.six.moves import input

def boolean_input(question, default=None):
result = input("%s " % question)
if not result and default is not None:
return default
while len(result) < 1 or result[0].lower() not in "yn":
result = input("Please answer yes or no: ")
return result[0].lower() == "y"

如果您的代码应该与 Python 2 和 3 兼容,请务必使用来自 django.utils.six.moves 的导入,或者如果您需要,请使用 raw_input()在 Python 2 上。Python 2 上的 input() 将评估输入而不是将其转换为字符串。

关于python - 向自定义 Django management/manage.py 命令添加确认步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39256578/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com