我有一个脚本,每天应该由crontab运行一次。这在我的桌面上工作正常。但是当我尝试在我的RPi上的virtualenv上运行它时,我收到了这个错误:
Traceback (most recent call last):
File "mailalert.py", line 7, in <module>
from django.contrib.auth.models import User
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/contrib/auth/__init__.py", line 5, in <module>
from django.middleware.csrf import rotate_token
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/middleware/csrf.py", line 16, in <module>
from django.utils.cache import patch_vary_headers
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/utils/cache.py", line 26, in <module>
from django.core.cache import get_cache
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/core/cache/__init__.py", line 70, in <module>
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/conf/__init__.py", line 46, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
看起来我无法使用:
from django.contrib.auth.models import User
有什么问题?
答案 0 :(得分:1)
DJANGO_SETTINGS_MODULE
在导入Django代码之前,您需要在DJANGO_SETTINGS_MODULE
脚本中配置mailalert.py
环境变量。
以下是你如何做到的:
#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "benchmarks.settings")
# Do you thing now.
请注意,您的代码现在可能没有在virtualenv中运行,正如程序包路径所证明的那样(/usr/local/lib
不是您的virtualenv):
"/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/contrib/auth/__init__.py"