Gunicorn多worker跑Flask应用Session数据共享问题

问题描述

使用Gunicorn设置多个worker跑flask应用后发现session状态存在各种紊乱的情况,使用session保存的用户登录状态过一会儿就丢失了,如果直接用python app.py跑的话一点问题也没有,日志中也看不出来有什么错误.

原因分析

Gunicorn中的worker实际上对应的是多进程,默认配置每个worker之间是独立存在的进程,也就是说每个worker会实例化一个新的Flask对象跑起来,这样的话如果代码中使用了随机变量作为sessionSECRET_KEY,那么每个worker都会生成不同的KEY,这样也就无法共享session中存放的键值了.

处理的办法

  1. 使用固定的SECRET_KEY
  2. 将要使用session存放的数据修改成写到数据库中,这样Gunicorn中使用worker实现的多进程之间就不会出现数据不同步的情况了.

参考资料

参考了stackoverflow上面的这个问题的回复:

https://stackoverflow.com/questions/30984622/flask-session-not-persistent-across-requests-in-flask-app-with-gunicorn-on-herok

Looks like there were two problems:

  • The app.secret_key shouldn’t be set to os.urandom(24) because every worker will have another secret key
  • For some reason the dict where I stored my sessions in was sometimes empty and sometimes not… Still haven’t found the reason for this though
    Storing the sessions in a database instead a dictionary at runtime solves the problem.
发布了186 篇原创文章 · 获赞 86 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/lpwmm/article/details/103951609