我有测试脚本:
#!/usr/bin/env python
# coding: utf-8
import os, sys, subprocess, time, re
from django.conf import settings
from django.apps import apps
import django
django.setup()
"""
http://stackoverflow.com/questions/24027901/dynamically-loading-django-apps-at-runtime
"""
MAIN_IMPORTS = """\
from django.test import TestCase
from model_mommy import mommy
"""
IMPORT_STATEMENT = """\
from clientsite.{app}.models import {models}
"""
TEST_BLOCK = """\
class {modelname}CreationTests(TestCase):
def setUp(self):
self.model = {modelname}
def test_create(self):
x = mommy.make(self.model)
x.save()
self.assertTrue(x.pk)
def test_factory_isinstance(self):
x = mommy.make(self.model)
self.assertTrue(isinstance(x, {modelname}))
"""
all_apps = apps.get_apps()
all_models = apps.get_models()
model_info = apps.all_models
我希望能够在我的脚本中使用django.apps
。该脚本位于mysite/mommy_app/scripts/testtasm.py
我试过
cchilders:~/work_projects/mysite [ckc/fixture-replacements]$ ./manage.py mysite/mommy_models/scripts/testtasm.py
Unknown command: 'mysite/mommy_models/scripts/testtasm.py'
并且失败了。
django.setup()
也失败了。
如何在脚本中使用django功能而不实际运行runserver?谢谢。
答案 0 :(得分:0)
除非您创建了custom management command
,否则您不应该使用manage.py
来运行您的脚本
您应该使用
运行脚本python mysite/mommy_models/scripts/testtasm.py
或者,如果脚本是可执行的
mysite/mommy_models/scripts/testtasm.py
在脚本中,在致电django.setup
之前,您必须设置DJANGO_SETTINGS_MODULE
环境变量。您可能还需要将项目目录添加到Python路径中。
import os
import sys
# This should be the directory that contains the directory containing settings.py
sys.path.add('/path/to/mysite')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()
# now you can import the settings and access them
from django.conf import settings