Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

python - Flask session not persistent across requests in Flask app with Gunicorn on Heroku

I'm running a Flask application with Gunicorn as a web server. The whole project is deployed to Heroku.

Procfile

web: gunicorn app:app --log-file=-

Flask sessions are implemented server side, only a session id is stored in the flask.session object. Whenever I'm trying to do a login, I get logged in correctly at first, but then get redirected to the starting site (which should be the user site).

LoginController.py

def login(form) :
    User.session.set(User.getByLogin(form))
    if User.session.exists() :
        return redirect(Urls.home)
    return redirect(Urls.login)

The log shows that User.session.exists() returns True but in the next method (during the redirect)...

HomeController.py

def view() :
    if User.session.exists() :
        return CourseController.view()
    return render_template("home.html")

...the same method returns False.

User.session object

def exists(self) :
    key = session.get("user_key")
    user = self.users.get(key)
    Log.debug("session::exists", user = user)
    return user is not None

In all following requests the user is randomly logged in or not.

What can be the reason for this? I heard that a too large session object can result in data loss, but I'm only storing integers in it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...