不正确的配置异常,但无论如何它都有效

问题描述 投票:-1回答:1

我有以下代码:

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文件中,只有env变量写为export VAR=VALUE列表。

所以我的问题是,为什么例外?

python django docker cron
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.