方法比较简单
import os
import base64
# 生成32位随机字符
a = os.urandom(32)
# 编码为base64
base64.b64encode(a)
Out[13]:
b'2QDq4HSpT8U4W6iZ2xDzGW3CcY2WVsJXVEwYv0qludY='
命令行中使用
python -c 'import base64;import os;print(base64.b64encode(os.urandom(32)).decode())'
DReeVwcWFxbuAJycdOWk3eHMslK+gv5vCz3W/o07VRk=
Flask文档也提供了一种方式
$ python -c 'import secrets; print(secrets.token_hex())'
192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf
参考: Flask】一种生成SECRET_KEY的方法 https://flask.palletsprojects.com/en/2.2.x/tutorial/deploy/?highlight=secret_key#configure-the-secret-key