为什么不在每次 Flask 启动时生成秘钥? [英] Why not generate the secret key every time Flask starts?

查看:22
本文介绍了为什么不在每次 Flask 启动时生成秘钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用会话时,Flask 需要一个密钥.在我见过的每个例子中,密钥都是以某种方式生成的,然后存储在源代码或配置文件中.

When using sessions, Flask requires a secret key. In every example I've seen, the secret key is somehow generated and then stored either in source code or in configuration file.

永久存储的原因是什么?为什么不直接在应用程序启动时生成它?

What is the reason to store it permanently? Why not simply generate it when the application starts?

app.secret_key = os.urandom(50)

推荐答案

密钥用于对会话 cookie 进行签名.如果您必须重新启动应用程序并重新生成密钥,则所有现有会话都将失效.这可能不是您想要的(或者至少不是使会话无效的正确方法).类似的情况也适用于依赖密钥的任何其他事物,例如由 itsdangerous 生成的令牌以提供重置密码 url(例如).

The secret key is used to sign the session cookie. If you had to restart your application, and regenerated the key, all the existing sessions would be invalidated. That's probably not what you want (or at least, not the right way to go about invalidating sessions). A similar case could be made for anything else that relies on the secret key, such as tokens generated by itsdangerous to provide reset password urls (for example).

应用程序可能因为崩溃、服务器重新启动、或者因为您正在推送错误修复或新功能、或者因为您使用的服务器产生新进程等而需要重新启动.因此您可以不要依赖服务器永远启动.

The application might need to be restarted because of a crash, or because the server rebooted, or because you are pushing a bug fix or new feature, or because the server you're using spawns new processes, etc. So you can't rely on the server being up forever.

标准做法是将一些一次性密钥提交到存储库(以便开发机器有东西),然后在部署时在本地配置中设置密钥.这样,密钥就不会泄露,也不需要重新生成.

The standard practice is to have some throwaway key commited to the repo (so that there's something there for dev machines) and then to set the key in the local config when deploying. This way, the key isn't leaked and doesn't need to be regenerated.

还有运行依赖于应用程序上下文的辅助系统的情况,例如用于运行后台任务的 Celery,或应用程序的多个负载平衡实例.如果应用程序的每个运行实例具有不同的设置,它们在某些情况下可能无法正确协同工作.

There's also the case of running secondary systems that depend on the app context, such as Celery for running background tasks, or multiple load balanced instances of the application. If each running instance of the application has different settings, they may not work together correctly in some cases.

这篇关于为什么不在每次 Flask 启动时生成秘钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆