Skip to content

Instantly share code, notes, and snippets.

@volodymyrsmirnov
Last active August 29, 2015 14:04
Show Gist options
  • Save volodymyrsmirnov/2d4369b36824b186159c to your computer and use it in GitHub Desktop.
Save volodymyrsmirnov/2d4369b36824b186159c to your computer and use it in GitHub Desktop.
from flask.ext.sqlalchemy import models_committed
app = Flask(__name__)
# Parent class for models that has to be inserted into the Elastic
class ElasticModelMixin(object):
__elastic_fields__ = []
def __elastic_insert__(self):
elastic_object = {}
for field in self.__elastic_fields__:
elastic_object[field] = getattr(self, field, None)
insert_to_elastic(self.__table_name__, self.id, elastic_object)
def __elastic_update__(self):
same_as_insert_but_update(self.__table_name__, self.id, elastic_object)
def __elastic_delete__(self):
delete_from_elastic(self.__table_name__, self.id)
# SQLAlchemy model with integration to Elastic
class Painting(db.Model, ElasticModelMixin):
__table_name__ = "painting"
__elastic_fields__ = ["name", "year", "description"]
id = db.Column(db.Integer())
name = db.Column(db.String())
year = db.Column(db.Integer())
description = db.Column(db.String())
# Flask-SQLAlchemy hooks
# See http://librelist.com/browser/flask/2010/8/3/flask-sqlalchemy-signal-support/
@models_committed.connect_via(app)
def on_models_committed(sender, changes):
for obj, change in changes:
# change = delete, update, insert
method_name = "__elastic_{0}__".format(change)
# get object method
method = getattr(obj, method_name, None)
# check if object has method
if callable(method):
method()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment