The following gist is an extract of the article Flask-SQLAlchemy Caching. It allows automated simple cache query and invalidation of cache relations through event among other features.
# pulling one User object
user = User.query.get(1)
# This is not used unless SQLALCHEMY_BINDS is not present | |
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{username}:{password}@{hostname}/{database}?charset=utf8' | |
SQLALCHEMY_BINDS = { | |
'master': 'mysql+pymysql://{username}:{password}@{hostname}/{database}?charset=utf8', | |
'slave': 'mysql+pymysql://{username}:{password}@{hostname}/{database}?charset=utf8' | |
} |
The following gist is an extract of the article Flask-SQLAlchemy Caching. It allows automated simple cache query and invalidation of cache relations through event among other features.
# pulling one User object
user = User.query.get(1)
This was going to be an answer to pallets-eco/flask-sqlalchemy#269 but I realised I was getting further away from answering the actual question.
How to make SQLAlchemy models that are reusable, and compatible with Flask-SQLAlchemy
I looked into doing something similar, in order to use SQLAlchemy models outside the app context and to automatically use some mixins for all models created, as well as to override the default table naming scheme.
Worth noting there are some unmerged PRs around overriding the metadata/base: pallets-eco/flask-sqlalchemy#61
The Model
and BaseQuery
classes are standalone -- it doesn't look like they require the instantiation, so you could import and inherit from them, or rewrite them to support what you need. The issue is then pulling your custom classes back into the SQLAlchemy()
part, since the class names are hardcoded.