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.