在尝试设置Flask-Debugtoolbar
时,我遇到了以下问题:
"DebugToolBar需要一个SECRET_KEY"。
我该从哪里获取SECRET_KEY
?
方法1:使用Python 2/3中的os
:
>>> import os
>>> os.urandom(12)
'\xf0?a\x9a\\\xff\xd4;\x0c\xcbHi'
方法 2:在 Python 2/3 中使用 uuid
:
>>> import uuid
>>> uuid.uuid4().hex
'3d6f45a5fc12445dbac2f59c3b6c7cb1'
方法3:使用Python >= 3.6中的secrets
模块:
>>> import secrets
>>> secrets.token_urlsafe(16)
'Drmhze6EPcv0fN_81Bj-nA'
>>> secrets.token_hex(16)
'8f42a73054b1749f8f58848be5e6502c'
方法4:使用Python 3中的os
:
>>> import os
>>> os.urandom(12).hex()
'f3cfe9ed8fae309f02079dbf'
方法1:使用app.secret_key
:
app.secret_key = 'the random string'
方法2:使用app.config
:
app.config['SECRET_KEY'] = 'the random string'
方法三: 将其放入您的配置文件中:
SECRET_KEY = 'the random string'
然后从配置文件中加载配置表单:
app.config.from_pyfile('config.py') # if your config file's name is config.py
为了保持客户端会话的安全,需要使用 秘密密钥。您可以按照以下方式生成一些随机密钥:
>>> import os
>>> os.urandom(24)
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'
只需将那个密钥复制粘贴到您的配置文件中即可。
SECRET_KEY = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'
请查看Sessions文档。
import os; print(os.urandom(24).hex())
。 - Daniel WaltripSECRET_KEY = os.urandom(24)
?我相信这会每次生成一个新的密钥,但这会有问题吗? - m13op22python -c "import os; print(os.urandom(24).hex())"
。 - erncyppython -c "print(__import__('os').urandom(24).hex())"
- Xbox OneSECRET_KEY
即可。app.config['SECRET_KEY'] = "Your_secret_string"
如果您有配置文件,只需将以下配置添加到其中:
SECRET_KEY = "Your_secret_string"
打开Python,在你的电脑上运行以下命令:
import secrets
secret_key = secrets.token_hex(16)
# example output, secret_key = 000d88cd9d90036ebdd237eb6b0db000
app.config['SECRET_KEY'] = secret_key
import secrets
from pathlib import Path
from flask import Flask
app = Flask(__name__)
SECRET_FILE_PATH = Path(".flask_secret")
try:
with SECRET_FILE_PATH.open("r") as secret_file:
app.secret_key = secret_file.read()
except FileNotFoundError:
# Let's create a cryptographically secure code in that file
with SECRET_FILE_PATH.open("w") as secret_file:
app.secret_key = secrets.token_hex(32)
secret_file.write(app.secret_key)
将机密信息存储在与版本控制代码分离的地方通常是一个好主意。Git非常擅长不丢失数据,包括秘密密钥和密码 :)
SECRET_KEY
的值:python -c 'import secrets; print(secrets.token_hex())'
在发布问题或提交代码时,不要透露秘密密钥。
我建议使用bcrypt哈希和十六进制进行哈希处理。
# IMPORT
from flask_bcrypt import Bcrypt
import secrets
secret_key = secrets.token_hex(16) #Create HEX Key
bcrypt = Bcrypt(app) #Init Bcrypt
secret_key_hash = bcrypt.generate_password_hash(secret_key) #hash the HEX key with Bcrypt
app.config['SECRET_KEY'] = secret_key_hash #setup secret key
# Output like: $2b$12$Y0QMIGwksa5OhtOBF9BczuAJ0hYMUv7esEBgMMdAuJ4V.7stwxT9e