How to execute external script in the Django environment(如何在 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 环境中执行外部脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Django 环境中执行外部脚本


- 我如何透明地重定向一个Python导入? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01