如何在Django中运行Python脚本?

o4hqfura  于 2023-05-16  发布在  Python
关注(0)|答案(1)|浏览(151)

我是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包含__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)
qvtsj1bj

qvtsj1bj1#

一般来说,最好将“ad-hoc”脚本(例如,您可以从命令行手动运行的任何脚本)重构为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在哪里。
(请记住在management/management/commands/文件夹中都有一个__init__.py文件。)

相关问题