如何在 Django 环境中执行外部脚本 [英] How to execute external script in the Django environment

查看:28
本文介绍了如何在 Django 环境中执行外部脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Django 控制台使用的环境中执行用于调试和类似终端目的的外部代码段,以便它可以连接到数据库等.

I am trying to execute an external snippet for debugging and terminal-like purposes in the environment the Django console uses so it can connect to the db, etc.

基本上,我使用它的原因与使用控制台的原因相同,但我使用更长的代码段来输出一些格式化信息,因此将代码放在使用 IDE 操作的实际文件中很方便.

Basically, I am just using it for the same reason one would fiddle with the console but I am using longer snippets to output some formatted information so it is handy to have that code in an actual file manipulated with an IDE.

答案说你可以通过执行 python manage.py shell <snippet.py 但我没有看到成功的结果.而且虽然没有报错,但我没有得到异常的输出,而只有一系列 >>> 提示.

An answer said you could do that by executing python manage.py shell < snippet.py but I did not see a successfull result. And although no errors are reported, I am not getting the excepted output, but only a series of >>> prompts.

那么我该怎么做呢?

顺便说一句,我正在使用 PyCharm,以防这个 IDE 有执行此操作的简写方式或任何特殊工具.

By the way, I am using PyCharm, in case this IDE has a shorthand way of doing this or any special tool.

推荐答案

我会说创建一个新的 自定义管理命令 是实现这一目标的最佳方式.

I would say creating a new Custom management command is the best way to achieve this goal.

但是您可以在 django 环境中运行您的脚本.我有时使用它来运行一次性脚本或一些简单的测试.

But you can run your script in a django environment. I use this sometimes to run a oneoff script or some simple tests.

您必须将环境变量 DJANGO_SETTINGS_MODULE 设置为您的设置模块,然后您必须调用 django.setup()

You have to set the environment variable DJANGO_SETTINGS_MODULE to your settings module and then you have to call django.setup()

我从 manage.py 脚本中复制了这些行,您必须设置正确的设置模块!

I copied these lines from the manage.py script, you have to set the correct settings module!

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")
django.setup()

这是一个我有时使用的简单模板脚本:

Here is a simple template script which I use sometimes:

# -*- coding: utf-8 -*-
import os
import django

#  you have to set the correct path to you settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")
django.setup()


from project.apps.bla.models import MyModel


def run():
    # do the work
    m = MyModel.objects.get(pk=1)


if __name__ == '__main__':
    run()

需要注意的是,所有项目导入都必须放在调用django.setup()之后.

It is important to note that all project imports must be placed after calling django.setup().

这篇关于如何在 Django 环境中执行外部脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆