How to reload a configuration file on each request for Flask?

后端 未结 1 1128
灰色年华
灰色年华 2020-12-21 14:58

Is there an idiomatic way to have Flask reload my configuration file on every request? The purpose of this would be so that I could change passwords or other configuration r

相关标签:
1条回答
  • 2020-12-21 15:00

    You cannot safely / correctly reload the config after the application begins handling requests. Config is only meant to be read during application setup. The main reason is because a production server will be running using multiple processes (or even distributed across servers), and the worker that handles the config change request does not have access to other workers to tell them to change. Additionally, some config is not designed to be reloaded, so even if you could notify all the other workers and get them to reload properly, it might not have any effect.

    Production WSGI servers can gracefully reload, that is they won't kill running workers until they've completed their responses, so downtime shouldn't actually be an issue. If it is (and it really isn't), then you're at such a large scale that you're beyond the scope of this answer.

    Graceful reload in:

    • Gunicorn
    • uWSGI
    • mod_wsgi

    If you need to use config that can be updated dynamically, you'll have to write all the code you use to expect that. You could use a before_request handler to load the config fresh each request. However, keep in mind that anything you didn't write that uses config may not expect the config to change.

    0 讨论(0)
提交回复
热议问题