gpt4 book ai didi

virtualenv 中的 Python 错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:46:07 26 4
gpt4 key购买 nike

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

问题是什么?

最佳答案

DJANGO_SETTINGS_MODULE

在导入 Django 代码之前,您需要在 mailalert.py 脚本中配置 DJANGO_SETTINGS_MODULE 环境变量。

具体操作方法如下:

#!/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"

关于virtualenv 中的 Python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19480672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com