如何在Django中运行python脚本?

时间:2019-10-08 12:59:56

标签: python django django-models

我是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)

1 个答案:

答案 0 :(得分:2)

通常,最好将“临时”脚本(例如您可以从命令行手动运行的任何脚本)重构为management commands

这样,一旦事情进入代码,就可以正确设置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在哪里。

(请记住,__init__.pymanagement/文件夹中都有一个management/commands/文件。)