1

I working on a Flask application that is deployed on heroku.
The application uses Flask-Session I need help to configure the server side session storage correctly.

I've first configured it to store sessions on server-side with Flask-Session configuration = "SESSION_FILE_DIR" = mkdtemp(). However, Heroku in this case it didn't run properly on this way. Heroku wouldn't store sessions and user will just log-out randomly. I've seen reccomendations to store sessions in database, rather than on server temp folder.

I've attempted to move to Database storage for the sessions, using "SESSION_TYPE" = "sqlalchemy". I have not been able to run this correctly to operate on locahost yet.

Followed this How to save sessions in a Postgres database? too, but with no success...

"""application.py"""

import os, datetime

from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session

# Import my package modules
from helpers import apology, login_required, status_mapper
from class_h import *

# Configure application
app = Flask(__name__)

# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

Original Session config ->

# # Configure session to use filesystem (instead of signed cookies)
# app.config["SESSION_FILE_DIR"] = mkdtemp()
# app.config["SESSION_PERMANENT"] = False
# app.config["SESSION_TYPE"] = "filesystem"
# Session(app)

My class_h.py model file imported in main file, creates db Instance, which is initialized in application.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# create a db but using flask_sqlalchemy syntax
db = SQLAlchemy()

Flask-SQLAlchemy config, Heroku Postgres database

app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)

Configure flask_session to use SQLAlchemy (instead of signed cookies)

app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "sqlalchemy"
Session(app)

After I've applied a [this fix] (https://github.com/mnbf9rca/flask-session/commit/9ad4b23e946beba1fdbd23dc406058a77dac6676) to the sessions.py file behaviour is that session record is not created in the database. If fix is not applied, session is created with None value.

tried with

from flask_sessionstore import Session

but I obtain same behaviour.

tried with:

["SESSION_PERMANENT"] = True

A session is created with Null expiry (instead of not being created).

I'd appreciate your help! spent days digging on this.

guruhitech
  • 173
  • 1
  • 3
  • 9
  • There is an issue while using flask-session because it stores everything on server-side when there is a load balancer(LB) behind your application. LB has different algorithms to distribute the load on servers. Suppose, 1st request does the user login related flask-session storage on 1st server, then on 2nd request which run on server 2 required previously stored flask-session on 1 server to give go-ahead to a user, but here it fails to detect any session. thus shows logged out user. – Rakesh Sharma May 13 '19 at 13:43
  • these links may help you https://stackoverflow.com/questions/10494431/sticky-and-non-sticky-sessions and https://www.reddit.com/r/flask/comments/4ox87q/question_about_flask_and_load_balancing_af/ – Rakesh Sharma May 13 '19 at 13:47
  • Good information about LB the configuration; however I understand that when storing session info in Postegres via SQLAlchemy session-type, data is operates as sticky session. I can confirm that if Flask-Session uses Redis as storage location, it does work as expected in Heroku. Still via Postgres it doesn't work. – guruhitech May 14 '19 at 11:17
  • Hi, have the same isuue here, what was your solution ? – Oris Apr 01 '22 at 07:38
  • @Oris as per above, I've moved to use Redis as the sessions storing configuration, which solved the issue – guruhitech Apr 04 '22 at 00:25

0 Answers0