1

我有一个脚本,它应该由 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

问题是什么?

4

1 回答 1

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"
于 2013-10-20T17:47:54.180 回答