如何通过外部 python 脚本在 Django shell 中执行代码?

How to execute code in the Django shell by an external python script?

我想达到的目标:

我想创建一个 python 脚本来从 CLI 中停用数据库中的 Django 用户。我想到了这个:

$ sudo python manage.py shell
>>> user = User.objects.get(username=FooBar)
>>> user.is_active = False
>>> user.save()
>>> exit()

当我在命令后手动输入它时,上面的代码有效。但是,我想将执行命令放在一个 .py 脚本中,例如

$ sudo python script.py

现在我尝试了不同的方法:

问题:

这不行! 我认为这个问题是因为 Python 一直等到打开的 Django shell(第一个命令)完成,而这是永远不会完成的。它不会执行脚本中的其余命令,因为第一个命令将其置于 Hold 状态。

subprocess.popen可以在shell中执行命令但是只能在Python中执行shell,我想用Djangoshell.

有人知道如何使用 .py 脚本访问 Django shell 以执行自定义代码吗?

尝试将命令输入 运行 django-shell 作为此处文档:

$ sudo python manage.py shell << EOF
user = User.objects.get(username=FooBar)
user.is_active = False
user.save()
exit()
EOF

首先,您不应该使用 sudo 访问您的 Python shell。无需 运行ning 作为 root。

其次,从命令提示符创建 运行 脚本的方法是编写自定义 manage.py 脚本,因此您可以 运行 ./manage.py deactivate_usersthe documentation.

中的完整说明

如果要执行访问Django模型的Python脚本,首先需要设置环境变量:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<path>.settings")

您需要将其中的 <path> 替换为您的项目目录,即包含文件 settings.py.

的目录

然后您可以导入您的模型文件,例如:

from <path>.models import User
user = User.objects.get(username=FooBar)
user.is_active = False
user.save()

根据 Daniel 早些时候在此线程中的评论,我创建了一个简单的脚本来完成工作。我正在为试图实现相同目标的该线程的读者分享此内容。该脚本将创建一个有效的“manage.py deactivate_user”函数。

这是您的 Django 应用程序文件夹结构的示例参考:

您想创建 "deactivate_user.py" 文件并将其放在 management/commands/deactivate_user.py 目录中。

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

class Command(BaseCommand):
    help = 'Deactivate user in the database'

    def handle(self, *args, **options):
        username = raw_input('Please type the username of the user you want remove: ')
        try:
            user = User.objects.get(username=username)
            user.is_active = False
            user.save()
            print ('User is now deactivated in the database.')
        except User.DoesNotExist:
            print ('Username not found')

使用“python manage.py deactivate_user”调用脚本您还可以创建一个 "activate_user" 脚本相同的代码,但不是 user.is_active = False 使用 = True.

打开 Django Shell python manage.py shell

然后运行execfile('filename.py')

如果您使用的是 Django 1.8+,那么另一个有用的选择是编写您自己的脚本,并使用 manage.py runscript 调用它。

比如你可以写一个名为db_init.py的脚本放在utils文件夹下
然后启动这个脚本:

python3 manage.py runscript utils.db_init

参考:
https://django-extensions.readthedocs.io/en/latest/runscript.html