During tests, Flask-Session intermittently causes the exception “sqlalchemy.exc.InvalidRequestError: Table 'sessions' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.” I'm presenting a workaround in this post.
I'm using pytest, and I've been experiencing intermittent tests failure due to exception “sqlalchemy.exc.InvalidRequestError: Table 'sessions' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.”. It only occurs if some tests are run together, run them individually one at a time, they pass. I've ignored this problem till a few days ago. Right now I have around 396 ( three hundreds and ninety six ) test cases, just by chance, I run some three ( 3 ) tests together, and two ( 2 ) consistently fail with the mentioned exception, only one ( 1 ) passes.
It turns out this is an ongoing issue with Flask-Session 0.4.0, and still persists in the latest version 0.4.0. Latest as on the 24th, November 2022.
My research led to the following post, among other posts which report the same issue:
How do you resolve 'Already defined in this MetaData Instance' Error with Flask Pytest, SqlAlchemy, and Flask Sessions? The answer by user Tassaron on 01/01/2021 leads to the following URLs:
- https://github.com/fengsp/flask-session/blob/1c1f7903184673682bd1d75432c8f455b62393a4/flask_session/sessions.py
- https://github.com/tassaron/muffin-shop/blob/main/src/helpers/main/session_interface.py
- https://github.com/fengsp/flask-session/pull/12
The general consensus seems to be only creating the Model for the database session table only if it does not already exists via the condition:
if table not in self.db.metadata:
It has been proposed a few years back, but for some reasons, it has not been implemented by the author.
Tassaron, herself, has implemented this in https://github.com/tassaron/muffin-shop/blob/main/src/helpers/main/session_interface.py:
class TassaronSessionInterface(SessionInterface):
...
def __init__(self, app, db):
...
if table not in self.db.metadata:
# ^ Only create Session Model if it doesn't already exist
# Fixes the SQLAlchemy "extend_existing must be true" exception during tests
class Session(self.db.Model):
...
self.sql_session_model = db.session_ext_session_model = Session
else:
self.sql_session_model = db.session_ext_session_model
Compared to the original Flask-Session 0.4.0:
class SqlAlchemySessionInterface(SessionInterface):
...
def __init__(self, app, db, table, key_prefix, use_signer=False,
permanent=True):
...
class Session(self.db.Model):
...
self.sql_session_model = Session
In TassaronSessionInterface, when the Session Model is first created, it also gets assigned to db new attribute session_ext_session_model, afterwards db.session_ext_session_model is used.
Apart from exceptions intermittently raised during tests, Flask-Session 0.4.0 works fine. I want to stick to it as much as possible. Following is my attempt, it feels like a workaround, a hack rather than a solution, I'm okay with this for the time being:
Content of fixed_session.py
from flask_session.sessions import SqlAlchemySessionInterface
from flask_session import Session
class FixedSqlAlchemySessionInterface( SqlAlchemySessionInterface ):
def __init__(self, app, db, table, key_prefix, use_signer=False,
permanent=True):
"""
Assumption: the way I use it, db is always a valid instance
at this point.
"""
if table not in db.metadata:
super().__init__( app, db, table, key_prefix, use_signer, permanent )
db.session_ext_session_model = self.sql_session_model
else:
# print( "`sessions` table already exists..." )
self.db = db
self.key_prefix = key_prefix
self.use_signer = use_signer
self.permanent = permanent
self.has_same_site_capability = hasattr(self, "get_cookie_samesite")
self.sql_session_model = db.session_ext_session_model
class FixedSession( Session ):
def _get_interface(self, app):
config = app.config.copy()
if config[ 'SESSION_TYPE' ] != 'sqlalchemy':
return super()._get_interface( app )
else:
config.setdefault( 'SESSION_PERMANENT', True )
config.setdefault( 'SESSION_KEY_PREFIX', 'session:' )
return FixedSqlAlchemySessionInterface(
app, config['SESSION_SQLALCHEMY'],
config['SESSION_SQLALCHEMY_TABLE'],
config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'],
config['SESSION_PERMANENT'] )
To use this implementation, import FixedSession as Session, then carry on as normal:
try:
from xxx.yyyy.fixed_session import FixedSession as Session
except ImportError:
from flask_session import Session
When Flask-Session is fixed, I can just remove fixed_session.py without needing to update any codes -- however, I should update the import, exceptions are expensive.
Back to my attempt, in FixedSqlAlchemySessionInterface, I copied the idea of db.session_ext_session_model from TassaronSessionInterface. The following lines are copied from the original codes:
self.db = db
self.key_prefix = key_prefix
self.use_signer = use_signer
self.permanent = permanent
self.has_same_site_capability = hasattr(self, "get_cookie_samesite")
That means, if Flask-Session gets updated without fixing this issue, I might have to update my codes!
In class FixedSession, the following lines in the overridden method def _get_interface(self, app):
config.setdefault( 'SESSION_PERMANENT', True )
config.setdefault( 'SESSION_KEY_PREFIX', 'session:' )
are also copied from the original codes, I never have SESSION_PERMANENT and SESSION_KEY_PREFIX in my environment variables file.
With, or without the “sessions” table in the database, my tests and application run with no problems. If I drop “sessions” table, it gets created as expected.
It's been fun investigating this issue. I'm not too happy with my code, but it works for me for the time being. Hopefully, the author will fix it in the future releases. In the meantime, I really do hope this post helps others whom come across this same problem. Thank you for reading and stay safe as always.
Top comments (11)
Hi there is a recent fix for this in 0.6.0. Please let me know if that works for you
Hi @lxstr,
First, thank you for your hard works. And do apologise for the late reply. I had been caught up in something else.
I have today just finished testing out Flask-Session new versions.
Following are what I have found out:
Version 0.6.0 works as you have stated. I have been able to run tests multiple without the stated error occured.
Version 0.8.0 is worse than version 0.4.0, it actually raises 3 ( three ) errors:
On Tests
This is the one that occurs using version 0.4.0:
This is the new one, which did not happen on version version 0.4.0:
The Application
This is the new one, which did not happen on version version 0.4.0:
Please note, I did also verify that version 0.4.0 causes error as has been described in post.
Thank you and best regards,
...behai.
Hi Behai, there were some changes from 0.6 to 0.8 but they 'should' have been improvements. From the errors I'm seeing it looks as if you are trying to subclass/override the interface and/or create tables or access the db attribute (which is internal and now renamed). There should ideally no longer be any need to do anything other than use the default interface, could you you confirm you are trying 0.8.0 without any such modifications or show me the specific lines the error occurs? Thanks!
Hi @lxstr,
Thank you for replying so quickly. What I did was verifying that "my errors" still occur using 0.4.0. And they do. Then I uninstalled 0.4.0, install 0.6.0, no errors occur for the tests or the application. Then I uninstalled 0.6.0, installed 0.8.0, then I got the three errors as reported in my previous reply, I ran it more than once, the errors were consistent. I then uninstalled 0.8.0, reinstalled 0.6.0 again. No errors, I ran everything more than once.
-- I tested both 0.6.0 and 0.8.0 with exactly the same code.
I have not looked into why the errors occur yet. I will do so in the next few days.
Thank you and best regards, Lex.
...behai.
Hi Lex,
My
E:\book-keeping\setup.py
, please noteFlask-Session=0.8.0
:My
E:\book-keeping\src\book_keeping\__init__.py
:Please note:
E:\book-keeping\src\book_keeping\library\
DOES NOT havefixed_session.py
module. I renamed it. Please see attached screenshot:My
E:\book-keeping\.env
:Full application error using version 0.8.0, "application" being
venv\Scripts\flask.exe run
:I can confirm that, after extracting the above error for this post, I went back to version 0.6.0, and everything works.
-- Please note that, to go back to version 0.6.0, I have to change the entry in
setup.py
to'Flask-Session=0.6.0',
, then manually install it with:Thank you and best regards,
...behai.
Hi Lex,
Just a little bit more info...
Regarding version 0.8.0, in
E:\book-keeping\src\book_keeping\__init__.py
, change to:from:
-- That is attribute
client
replaced attributedb
. The application runs.However, my test still results in error:
as per version .0.4.0.
Thank you and best regards,
...behai.
Hi Lex,
For version 0.8.0, in
sqlalchemy\sqlalchemy.py
, I copy the following from 0.6.0:to replace:
That is:
And errors disappear. The tests and the application work.
Thank you and best regards,
...behai.
Ok I may decide to add again the "keep_existing": True, however this shouldn't be needed. If you delete or comment the following lines and use 0.8.0, I would be interested to know the result. There should be no need to manually create the table as flask-session does this now.
and
with app.app_context():
Hi Lex,
Based on your advice:
E:\book-keeping\src\book_keeping\__init__.py
modified to:I have also decided to use latest of everything,
E:\book-keeping\setup.py
updated to:I am using the original
Flask-Session 0.8.0
:Test 1: table
sessions
exists:The application runs. That is,
venv\Scripts\flask.exe run
does not raise exception.Tests no longer raise the table
sessions
exists exception. They now raise another unrelated exception.Test 2: I manually removed the existing
sessions
table:The results are as in Test 1. BUT THE TABLE
sessions
DOES NOT GET CREATED.Further note:
With:
Tests raise the old exception (0.4.0). But the
sessions
table gets created.venv\Scripts\flask.exe run
no longer raises the old exception (0.4.0) and the tablesessions
table also gets created.Please note that, I posted this article on the 24th, November 2022. And labelled the code for this article. That is why I am able to get the code test this problem. I forgot to label database version!
Since the this article, I added more functionalities including database changes till around May 2023, I have since stopped working on this project.
For these tests, for the application (that is,
venv\Scripts\flask.exe run
), I can only get to the login page. But that should be enough.Please let me know if you want me to do anything else.
Thank you and best regards,
...behai.
Hi @lxstr,
Your advice works.
And this report from my last response is not correct:
There was something in my code what caused it not to work. I am using all latest packages now.
There is no need for:
I do apologise for all the fault alarms. I appreciate your helps.
Thank you and best regards,
...behai.
P.S.
Just a side note, my application has a view session functionality for admins, whereby it just displays existing sessions as JSON. I was using
pickle
to serialise the session data.Flask-Session 0.8.0
now usesmsgspec
, the serialisation ofsessions.data
is now:Hi Lex,
I am sorry for my late reply. Thank you very much. I will have a look at it. I have been working on some other things.
Thank you and best regards,
...behai.