为什么Django在从脚本启动但不是以交互方式启动时会出现设置错误?

时间:2014-09-01 20:06:21

标签: python django multiprocessing

我尝试使用一些固定数据启动迷你Django测试服务器进行测试。

当以交互方式(从REPL)循环运行时,它正确运行,当由python myscript.py作为脚本的一部分执行时,它会失败。我猜测环境中有什么不同,但是什么?

代码:

import os
import sys
import json
import resttest
import unittest
from multiprocessing import Process
from django.core.management import execute_from_command_line

server_process = None
prefix = 'http://localhost:8000'

path = os.getcwd()
os.chdir('testapp') # Django project is separate and in subfolder 'testapp'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testapp.settings")
config_args = list()
config_args.append('')
config_args.append('testserver')
config_args.append('test_data.json')
proc = Process(target=execute_from_command_line, args=[config_args])
proc.start()
os.chdir(path)

错误:

Process Process-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 261, in fetch_command
    commands = get_commands()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 107, in get_commands
    apps = settings.INSTALLED_APPS
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 54, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 49, in _setup
    self._wrapped = Settings(settings_module)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 132, in __init__
    % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'testapp.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named testapp.settings

上下文

我正在开发一个用于测试的小型Python项目&基准测试REST服务。它利用pycurl绑定提供对发出的HTTP请求的低级控制,以方便测试。为了确保正确使用pycurl,我创建了一个基本的Django REST API,用于功能测试。

2 个答案:

答案 0 :(得分:5)

testapp/的父目录添加到Python路径。

sys.path.append("/path/to/directory/")

您当然可以通过编程方式确定此位置;用于执行此操作的命令取决于脚本与testapp位置的比较位置。您可以删除os.getcwd()os.chdir()。重要的是PYTHONPATH,而不是工作目录。您正确指定了设置模块环境变量,但the docs记录了正确设置Python导入搜索路径。

除了1:看看django.core.management.call_command。虽然您仍需要设置设置模块,但这是一个快捷方式。 call_command('testserver', 'test_data.json')

除了2:您可以跳过设置docs here中提到的环境变量。在你的情况下:

from django.conf import settings
from testapp import settings as my_settings

settings.configure(my_settings)

答案 1 :(得分:0)

如何将export PYTHONPATH=$PYTHONPATH:$PWD添加到.env