问题
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.
回答1:
Looks like there were two problems:
- The
app.secret_key
shouldn't be set toos.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.
回答2:
I had a similar issue, but for me the answer was related to the cookies. A new session was being created when I opened my development environment, then another one when going to google, and a new one after a successful log in.
The problem was that my SESSION_COOKIE_DOMAIN was incorrect, and the cookie domain was being set to a different host. For my local development purposes I set SESSION_COOKIE_DOMAIN = '127.0.0.1', and use http://127.0.0.1: to access it, and it works OK now.
来源:https://stackoverflow.com/questions/30984622/flask-session-not-persistent-across-requests-in-flask-app-with-gunicorn-on-herok