我有以下代码:
import django
def process():
django.setup()
from django.conf import settings
print(settings.configured())
print(settings.SECRET_KEY)
if __name__ == "__main__":
process()
当我尝试在docker内部使用cron定义的所有env变量运行它时,我得到:
cron_1 | Traceback (most recent call last):
cron_1 | File "process_tasks.py", line 16, in <module>
cron_1 | process()
cron_1 | File "process_tasks.py", line 8, in process
cron_1 | django.setup()
cron_1 | File "/usr/local/lib/python3.7/dist-packages/django/__init__.py", line 19, in setup
cron_1 | configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
cron_1 | File "/usr/local/lib/python3.7/dist-packages/django/conf/__init__.py", line 57, in __getattr__
cron_1 | self._setup(name)
cron_1 | File "/usr/local/lib/python3.7/dist-packages/django/conf/__init__.py", line 42, in _setup
cron_1 | % (desc, ENVIRONMENT_VARIABLE))
cron_1 | django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
cron_1 | app.settings.dev
cron_1 | True
cron_1 | dev
当我不使用cron运行它时,我没有得到异常。 但是,即使有例外,一切似乎都可以正常工作。对于cronjob,我正在使用:
* * * * * root . /root/env.sh; cd /app/; python3 process_tasks.py > /proc/1/fd/1 2>/proc/1/fd/2
在env.sh文件中,只存在写为export VAR=VALUE
列表的env变量。
所以我的问题是,为什么要例外?
答案 0 :(得分:1)
错误消息的关键部分是:
> You must either define the environment variable DJANGO_SETTINGS_MODULE
您可以在您体内完成
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
或者您可以将其导出到您的env.sh
export DJANGO_SETTINGS_MODULE=mysite.settings