问题描述

使用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.
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐