Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

python - How to execute external script in the Django environment

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.

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.

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.

So how can I do this?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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()

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...