gpt4 book ai didi

python - 保留 key

转载 作者:IT老高 更新时间:2023-10-28 22:09:25 30 4
gpt4 key购买 nike

local_settings.py 反模式的原因之一是把 SECRET_KEY, AWS设置文件中的键等值有问题:

  • secret 通常应该是这样的: secret !将它们保存在版本控制中意味着拥有存储库访问权限的每个人都可以访问它们。

我的问题是如何将所有 key 保密?

最佳答案

最初的问题是关于如何在环境变量中保密。这在本书 Two Scoops of Django 中有广泛的讨论。 .下面是他们所说的摘要,然后是关于使用这种技术的警告。

从 1.11 版的第 48 页(第 5.3 节)开始:

Every operating system supported by Django (and Python) provides the easy capability to create environment variables.

Here are the benefits of using environment variables for secret keys:

  • Keeping secrets out of settings allows you to store every settings file in version control without hesitation. All of your Python code really should be stored in version control, including your settings.
  • Instead of each developer maintaining their own copy-and-pasted version of local_settings.py.example for development, everyone shares the same version-controlled settings/local.py .
  • System administrators can rapidly deploy the project without having to modify files containing Python code.
  • Most platforms-as-a-service recommend the use of environment variables for configuration and have built-in features for setting and managing them.

在下一页,本书继续:

Before you begin setting environment variables, you should have the following:

  • A way to manage the secret information you are going to store.
  • A good understanding of how bash settings work on servers, or a willingness to have your project hosted by a platform-as-a-service.

他们描述了如何在本地和生产环境中设置环境变量(以 Heroku 为例——您需要检查您是否使用不同的主机,这只是一种可能性):

How To Set Environment Variables Locally
export SOME_SECRET_KEY=1c3-cr3am-15-yummy

How To Set Environment Variables in Production
heroku config:set SOME_SECRET_KEY=1c3-cr3am-15-yummy

最后,在第 52 页,他们给出了如何访问 key 的说明。例如,您可以将下面的前两行放在您的设置文件中,以替换默认放置在那里的原始 key 字符串:

>>> import os
>>> os.environ['SOME_SECRET_KEY']
'1c3-cr3am-15-yummy'

This snippet simply gets the value of the SOME_SECRET_KEY environment variable from the operating system and saves it to a Python variable called SOME_SECRET_KEY.

Following this pattern means all code can remain in version control, and all secrets remain safe.

请注意,这在某些情况下不起作用,例如,如果您使用的是 Apache 服务器。要处理这种模式不起作用的情况,您应该查看他们书中的第 5.4 节(“当您无法使用环境变量时”)。在这种情况下,他们建议使用 secret 文件。

截至 2017 年底,这种在环境变量中存储 secret 的技术是两勺和十二因素应用程序设计模式中推荐的最佳实践。在 Django 文档中也推荐使用它。但是,存在一些安全风险:如果某些开发人员或某些代码可以访问您的系统,他们将可以访问您的环境变量,并且可能会无意(或有意)将它们公开。 Michael Reinsch 在这里提出了这一点:
http://movingfast.io/articles/environment-variables-considered-harmful/

关于python - 保留 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14786072/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com