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

查看:60
本文介绍了为什么在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进行签名.如果必须重新启动应用程序并重新生成密钥,则所有现有会话都将失效.那可能不是您想要的(或者至少不是使会话无效的正确方法).对于依赖于秘密密钥的其他任何事物,例如由其危险生成的令牌(例如提供重置密码网址),都可能发生类似的情况.

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.

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

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天全站免登陆