Skip to content

Commit

Permalink
Add option to defer table creation; allows management of table and sc…
Browse files Browse the repository at this point in the history
…hema by other tooling (like Flask-Migrate)
  • Loading branch information
Lee Goolsbee committed Apr 17, 2024
1 parent 1e3a1cb commit b2db95f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
4 changes: 4 additions & 0 deletions src/flask_session/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ def _get_interface(self, app):
SESSION_SQLALCHEMY_TABLE = config.get(
"SESSION_SQLALCHEMY_TABLE", Defaults.SESSION_SQLALCHEMY_TABLE
)
SESSION_SQLALCHEMY_CREATE_TABLE = config.get(
"SESSION_SQLALCHEMY_CREATE_TABLE", Defaults.SESSION_SQLALCHEMY_CREATE_TABLE
)
SESSION_SQLALCHEMY_SEQUENCE = config.get(
"SESSION_SQLALCHEMY_SEQUENCE", Defaults.SESSION_SQLALCHEMY_SEQUENCE
)
Expand Down Expand Up @@ -166,6 +169,7 @@ def _get_interface(self, app):
**common_params,
client=SESSION_SQLALCHEMY,
table=SESSION_SQLALCHEMY_TABLE,
create_table=SESSION_SQLALCHEMY_CREATE_TABLE,
sequence=SESSION_SQLALCHEMY_SEQUENCE,
schema=SESSION_SQLALCHEMY_SCHEMA,
bind_key=SESSION_SQLALCHEMY_BIND_KEY,
Expand Down
1 change: 1 addition & 0 deletions src/flask_session/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class Defaults:
SESSION_SQLALCHEMY_SEQUENCE = None
SESSION_SQLALCHEMY_SCHEMA = None
SESSION_SQLALCHEMY_BIND_KEY = None
SESSION_SQLALCHEMY_CREATE_TABLE = True

# DynamoDB settings
SESSION_DYNAMODB = None
Expand Down
17 changes: 10 additions & 7 deletions src/flask_session/sqlalchemy/sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ def __init__(
sequence: Optional[str] = Defaults.SESSION_SQLALCHEMY_SEQUENCE,
schema: Optional[str] = Defaults.SESSION_SQLALCHEMY_SCHEMA,
bind_key: Optional[str] = Defaults.SESSION_SQLALCHEMY_BIND_KEY,
create_table: bool = Defaults.SESSION_SQLALCHEMY_CREATE_TABLE,
cleanup_n_requests: Optional[int] = Defaults.SESSION_CLEANUP_N_REQUESTS,
):
self.app = app
Expand All @@ -103,13 +104,15 @@ def __init__(
self.sql_session_model = create_session_model(
client, table, schema, bind_key, sequence
)
# Create the table if it does not exist
with app.app_context():
if bind_key:
engine = self.client.get_engine(app, bind=bind_key)
else:
engine = self.client.engine
self.sql_session_model.__table__.create(bind=engine, checkfirst=True)

# Optionally create the table if it does not exist
if create_table:
with app.app_context():
if bind_key:
engine = self.client.get_engine(app, bind=bind_key)
else:
engine = self.client.engine
self.sql_session_model.__table__.create(bind=engine, checkfirst=True)

super().__init__(
app,
Expand Down

0 comments on commit b2db95f

Please sign in to comment.