pallets-eco / flask-session

Server side session extension for Flask
https://flask-session.readthedocs.io
BSD 3-Clause "New" or "Revised" License
501 stars 239 forks source link

Problem with session_type sqlalchemy: AttributeError: 'str' object has no attribute 'Model' #118

Closed 2327 closed 3 years ago

2327 commented 4 years ago

Hello. I use docker - python:3.7-alpine, Flask-SocketIO==4.2.1, Flask-SQLAlchemy==2.4.1, Flask-Session==0.3.1. If i use SESSION_TYPE = 'filesystem' then all rigth. But if i use SESSION_TYPE = 'sqlalchemy' then i have problem.

.flaskenv:

SESSION_TYPE = 'sqlalchemy' SESSION_SQLALCHEMY = 'sqlite:///flask_app.sqlite3' SESSION_SQLALCHEMY_TABLE = 'sessions' SESSION_PERMANENT = True PERMANENT_SESSION_LIFETIME = 300

config.py:

import os from dotenv import load_dotenv load_dotenv(dotenv_path='.flaskenv', verbose=False) class Config: ... SESSION_TYPE = os.getenv("SESSION_TYPE") SESSION_SQLALCHEMY = os.getenv("SESSION_SQLALCHEMY") SESSION_SQLALCHEMY_TABLE = os.getenv("SESSION_SQLALCHEMY_TABLE") SESSION_PERMANENT = bool(os.getenv("SESSION_PERMANENT")) PERMANENT_SESSION_LIFETIME = os.getenv("PERMANENT_SESSION_LIFETIME")

sockets.py:

from flask import Flask, render_template, request, session from flask_session import Session ... app = Flask(name) sess = Session() sess.init_app(app)

Output:

Traceback (most recent call last): File "sockets.py", line 24, in <module> sess.init_app(app) File "/usr/local/lib/python3.7/site-packages/flask_session/__init__.py", line 61, in init_app app.session_interface = self._get_interface(app) File "/usr/local/lib/python3.7/site-packages/flask_session/__init__.py", line 105, in _get_interface config['SESSION_PERMANENT']) File "/usr/local/lib/python3.7/site-packages/flask_session/sessions.py", line 478, in __init__ class Session(self.db.Model): AttributeError: 'str' object has no attribute 'Model'

rajacs50 commented 4 years ago

I'm facing the same problem. I'm running the flask application on my local windows machine. Works fine with local file system. Getting this error if I try to use SQLAlchemy.

jlbgit commented 4 years ago

I think you need to import the db object directly, I solved this by changing config.py:


from X import db

# where X is the location where you define db = SQLAlchemy()

SESSION_SQLALCHEMY = db
fengsp commented 3 years ago

@jlbgit explained it correctly.