如何在Django中运行Python脚本?

3

我是Django的新手,我正在尝试像在views.py中那样,在脚本中导入我的一个模型。但是我遇到了一个错误:

Traceback (most recent call last):

  File "CallCenter\make_call.py", line 3, in <module>

    from .models import Campaign


ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package

我的文件结构如下:

MyApp\CallCenter\

CallCenter包含__init__.pymake_call.pymodels.pyviews.py,而MyApp有manage.py

from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse, Say, Dial, Number, VoiceResponse
from .models import Campaign


def create_xml():

    # Creates XML
    response = VoiceResponse()
    campaign = Campaign.objects.get(pk=1)
    response.say(campaign.campaign_text)

    return response


xml = create_xml()
print(xml)

你是如何调用 make_call.py 的?在 CallCenter 应用程序目录中使用 python make_call.py 是行不通的。 - AKX
@AKX 我运行了以下命令(venv)C:\Users\Username\PycharmProjects\MyApp>python CallCenter\make_call.py - Ayodele Ashad
1
你不能像运行其他Python脚本一样在Django项目中直接运行Python文件:Django需要进行整个设置来加载你的应用和模型(django.setup()),这是必须的,以便能够使用你的模型等等... 如果你想使用Django运行类似命令行的脚本,请创建一个管理命令,这样你就可以使用manage.py运行它,它会为你做正确的设置。 - dirkgroten
1个回答

5

总的来说,最好将“临时”脚本——比如你可能会从命令行手动运行的任何脚本——重构为管理命令

这样一来,在代码运行到你的程序之前,Django运行时已经正确地设置好了,你还可以免费获得命令行解析。

你的make_call.py可能会变成这样:

CallCenter/management/commands/make_call.py

from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse, Say, Dial, Number, VoiceResponse
from CallCenter.models import Campaign

from django.core.management import BaseCommand


def create_xml(campaign):
    # Creates XML
    response = VoiceResponse()
    response.say(campaign.campaign_text)
    return response


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument("--campaign-id", required=True, type=int)

    def handle(self, campaign_id, **options):
        campaign = Campaign.objects.get(pk=campaign_id)
        xml = create_xml(campaign)
        print(xml)

它将被调用,并且需要使用

$ python manage.py make_call --campaign-id=1

从你的manage.py所在的任何地方执行。

(请记得在management/management/commands/文件夹中都有一个__init__.py文件。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接