Python 在生产设置中使用 django 提高 KeyError(key) KeyError: 'SECRET_KEY'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28090391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:43:41  来源:igfitidea点击:

getting raise KeyError(key) KeyError: 'SECRET_KEY' with django on production settings

pythondjangokeyerror

提问by sidx

I've 2 separate settings files for production and development and a common base.py settings file
base.py

我有 2 个单独的用于生产和开发的设置文件和一个通用的 base.py 设置文件
base.py

SECRET_KEY = r"!@#$%^&123456"

prod.py

产品.py

from .base import *
SECRET_KEY = os.environ['SECRET_KEY']

manage.py

管理文件

#!/usr/bin/env python
import os

import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.dev")

from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)

When I enter this in terminal:

当我在终端中输入时:

python manage.py shell --settings=entri.settings.prod

I get error:

我得到错误:

raise KeyError(key)
KeyError: 'SECRET_KEY'

Help me, I'm new to django and python

帮帮我,我是 Django 和 python 的新手

采纳答案by u1860929

I think you are trying this locally, and don't have the SECRET_KEYsetup in your environment.

我认为您正在本地尝试此操作,并且SECRET_KEY您的环境中没有设置。

Set it using

设置它使用

export SECRET_KEY="somesecretvalue"

and then running python manage.py shell --settings=entri.settings.prodshould work fine.

然后运行python manage.py shell --settings=entri.settings.prod应该可以正常工作。

回答by Chandru

I use os.getenv('SECRET_KEY'), instead of os.environ['SECRET_KEY']

我使用 os.getenv('SECRET_KEY'),而不是 os.environ['SECRET_KEY']

print os.getenv('SECRET_KEY')    #returns None if KEY doesn't exist
print os.getenv('SECRET_KEY', 0) #will return 0 if KEY doesn't exist 

my python version is 2.7.12

我的 python 版本是 2.7.12