有时我想在我的 Django 项目的上下文中执行一个文件,就像我在使用 shell 一样,但使用文本编辑器很方便。这主要是在将其放入视图、测试、重复任务或管理命令之前尝试一些东西,或者快速原型化一些功能。
我知道我可以将这些行放在 .py 文件的顶部,它将在 Django 上下文中运行:
import sys
sys.path.append('/location/of/projet')
from django.core.management import setup_environ
import settings
setup_environ(settings)
我认为制作一个带有参数的管理命令、一个要运行的 python 模块并在 Django 环境中执行它会更容易。这是我写的'runmodule'命令:
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Runs an arbitrary module, in the Django environment, for quick prototyping of code that's too big for the shell."
def handle(self, *args, **options):
if not args:
return
module_name = args[0]
try:
__import__(module_name)
except ImportError:
print("Unable to import module %s. Check that is within Django's PYTHONPATH" % (module_name))
这看起来可行——我可以在模块中粘贴一些代码,并将其作为参数传递给该命令,它会被执行,例如
python manage.py runmodule myapp.trysomethingout
这将执行 myapp/trysomethingout.py。这是最好的方法吗?