Pycharm:为运行 manage.py 任务设置环境变量 [英] Pycharm: set environment variable for run manage.py Task
问题描述
我已将我的 SECRET_KEY
值移出我的设置文件,并在我加载我的 virtualenv 时设置它.我可以从 python manage.py shell
确认该值存在.
I have moved my SECRET_KEY
value out of my settings file, and it gets set when I load my virtualenv. I can confirm the value is present from python manage.py shell
.
当我运行 Django 控制台时,SECRET_KEY
丢失了,这是应该的.所以在首选项中,我转到 Console>Django Console 并加载 SECRET_KEY
和适当的值.我回到 Django 控制台,SECRET_KEY
在那里.
When I run the Django Console, SECRET_KEY
is missing, as it should. So in preferences, I go to Console>Django Console and load SECRET_KEY
and the appropriate value. I go back into the Django Console, and SECRET_KEY
is there.
正如预期的那样,我还不能运行 manage.py 任务,因为它还没有找到 SECRET_KEY
.因此,我进入 Run>Edit Configurations 以将 SECRET_KEY
添加到 Django 服务器和 Django 测试以及项目服务器中.重启Pycharm,确认键.
As expected, I cannot yet run a manage.py Task because it has yet to find the SECRET_KEY
. So I go into Run>Edit Configurations to add SECRET_KEY
into Django server and Django Tests, and into the project server. Restart Pycharm, confirm keys.
当我运行一个 manage.py 任务时,例如 runserver
,我仍然得到 KeyError: 'SECRET_KEY'.
When I run a manage.py Task, such as runserver
, I still get KeyError: 'SECRET_KEY'.
我把这个钥匙放在哪里?
Where do I put this key?
推荐答案
因为 Pycharm 不是从终端启动,所以不会加载您的环境.简而言之,任何 GUI 程序都不会继承 SHELL 变量.请参阅此了解原因(假设是 Mac).
Because Pycharm is not launching from a terminal, your environment will not be loaded. In short, any GUI program will not inherit the SHELL variables. See this for reasons (assuming a Mac).
然而,这个问题有几个基本的解决方案.正如 @user3228589 发布的那样,您可以将其设置为 PyCharm 中的变量.这有几个优点和缺点.我个人不喜欢这种方法,因为它不是单一源
.为了解决这个问题,我在 settings.py 文件的顶部使用了一个小函数,它在本地 .env
文件中查找变量.我把我所有的私人"东西都放在那里.我也可以在我的 virtualenv 中引用它.
However, there are several basic solutions to this problem. As @user3228589 posted, you can set this up as a variable within PyCharm. This has several pros and cons. I personally don't like this approach because it's not a single source
. To fix this, I use a small function at the top of my settings.py file which looks up the variable inside a local .env
file. I put all of my "private" stuff in there. I also can reference this in my virtualenv.
这是它的样子.
--settings.py
-- settings.py
def get_env_variable(var_name, default=False):
"""
Get the environment variable or return exception
:param var_name: Environment Variable to lookup
"""
try:
return os.environ[var_name]
except KeyError:
import StringIO
import ConfigParser
env_file = os.environ.get('PROJECT_ENV_FILE', SITE_ROOT + "/.env")
try:
config = StringIO.StringIO()
config.write("[DATA]
")
config.write(open(env_file).read())
config.seek(0, os.SEEK_SET)
cp = ConfigParser.ConfigParser()
cp.readfp(config)
value = dict(cp.items('DATA'))[var_name.lower()]
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
elif value.startswith("'") and value.endswith("'"):
value = value[1:-1]
os.environ.setdefault(var_name, value)
return value
except (KeyError, IOError):
if default is not False:
return default
from django.core.exceptions import ImproperlyConfigured
error_msg = "Either set the env variable '{var}' or place it in your "
"{env_file} file as '{var} = VALUE'"
raise ImproperlyConfigured(error_msg.format(var=var_name, env_file=env_file))
# Make this unique, and don't share it with anybody.
SECRET_KEY = get_env_variable('SECRET_KEY')
那么 env 文件是这样的:
Then the env file looks like this:
#!/bin/sh
#
# This should normally be placed in the ${SITE_ROOT}/.env
#
# DEPLOYMENT DO NOT MODIFY THESE..
SECRET_KEY='XXXSECRETKEY'
最后你的 virtualenv/bin/postactivate 可以获取这个文件.您可以进一步导出变量,如 此处 如果您愿意,但由于设置文件直接调用 .env,因此实际上没有必要.
And finally your virtualenv/bin/postactivate can source this file. You could go further and export the variables as described here if you'd like, but since settings file directly calls the .env, there isn't really a need.
这篇关于Pycharm:为运行 manage.py 任务设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!