Git / Heroku-如何隐藏我的SECRET_KEY? [英] Git/Heroku - How to hide my SECRET_KEY?
问题描述
我正在使用Python和Django创建一个Heroku Web应用,在命令'git push heroku master'之后,Heroku给了我这个错误: ModuleNotFoundError:没有名为'dlist.secret_settings'的模块
尝试执行此操作时:
Im using Python and Django to create a Heroku web app and Heroku gives me this error after the command 'git push heroku master': ModuleNotFoundError: No module named 'dlist.secret_settings'
when attempting to do this:
#settings.py
from .secret_settings import *
# from secret_settings.py import * doesn't work for some reason.
这是secret_settings.py(与settings.py在同一文件夹中)包含的内容:
Here is what secret_settings.py (which is in the same folder as settings.py) contains:
#secret_settings.py
SECRET_KEY = 'string here'
问题是,当我在本地服务器上测试我的Web应用程序(即 http://127.0.0.1:8000/ ),但是当我将这些更改推送到Heroku时,它不起作用。正如您所看到的,我只想隐藏我的SECRET_KEY。我查看了其他建议,但似乎无法弄清楚,选择这种方法是因为它可以理解。非常沮丧。初学者友好的答案/步骤,我们将不胜感激。
The problem is, this works when I test my web app on my local server (ie http://127.0.0.1:8000/), but its not working when I push these changes to Heroku. All I want to do is hide my SECRET_KEY, per others advice, as you can see. Ive looked at others suggestions and I can't seem to figure it out, choosing this method because it was understandable. Very frustrating. Beginner friendly answers/steps are greatly appreciated.
推荐答案
我猜您已将Git配置为忽略 secret_settings.py
。这是我想到创建单独文件的唯一原因。
I'm guessing you've configured Git to ignore secret_settings.py
. That's the only reason I can think of to create a separate file.
Heroku部署由Git驱动。由于Git不会跟踪 secret_settings.py
,因此不会将其推送到Heroku。您可以将文件添加到存储库中,但是这样一来就无法实现单独放置未跟踪文件的目的。
Heroku deploys are powered by Git. Since secret_settings.py
isn't tracked by Git it doesn't get pushed to Heroku. You could add the file to your repository, but that would defeat the purpose of having a separate untracked file in the first place.
解决方案是使用环境变量。这是在Heroku上受到良好支持的。
The solution is to use an environment variable. This is well-supported on Heroku.
在您的 settings.py
文件中,使用 os.getenv()
像这样:
In your settings.py
file, set your SECRET_KEY
using os.getenv()
like this:
import os
SECRET_KEY = os.getenv('SECRET_KEY', 'Optional default value')
这告诉Django从以下位置加载 SECRET_KEY
设置一个名为 SECRET_KEY
的环境变量。如果不存在这样的环境变量,它将退回到可选的默认值。
This tells Django to load your SECRET_KEY
setting from an environment variable called SECRET_KEY
. If no such environment variable exists it will fall back to the optional default value. On your development machine it's probably fine to use the default.
最后,在Heroku上设置 SECRET_KEY
环境变量。您可以通过运行 heroku config:在开发计算机上或通过Heroku基于Web的仪表板设置SECRET_KEY = YOUR_SECRET_KEY_VALUE
。
Finally, set the SECRET_KEY
environment variable on Heroku. You can do this by running heroku config:set SECRET_KEY="YOUR_SECRET_KEY_VALUE"
on your development machine, or via Heroku's web-based dashboard.
不再需要您的 secret_settings.py
文件。
这篇关于Git / Heroku-如何隐藏我的SECRET_KEY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!