Jawbone Health Flask-SQLAlchemy base model and mixins
To use the base model:
- Set it as the model_class when creating the flask_sqlalchemy object:
import flask_sqlalchemy
import jhhalchemy.model
db = flask_sqlalchemy.SQLAlchemy(app, model_class=jhhalchemy.model.Base)
- Your application's models should inherit from flask_sqlalchemy's Model and define Columns with SQLAlchemy's objects:
class MyModel(db.Model):
my_id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
- The Base.save and Base.delete methods require passing in a session object. In most cases use the the one from flask_sqlalchemy:
my_model = MyModel()
my_model.save(db.session)
my_model.delete(db.session)
To use a jhhalchemy mixin, simply include it in your model's inheritance list:
import jhhalchemy.model.time_order
class MyTimeOrderModel(db.Model, jhhalchemy.model.time_order.TimeOrderMixin):
"""
Define additional columns, etc.
"""
my_col = db.Column(...)
@classmethod
def my_read_range(cls, my_col_value, start_timestamp, end_timestamp):
cls.read_time_range(my_col == my_col_value, start_timestamp=start_timestamp, end_timestamp=end_timestamp)
The time_order mixin has a helper function called get_by_range
. The module provides this function because we were
writing some form of it for every model that used time_order. Here is an example of a model-specific wrapper:
def get_locations_by_range(uid, start_timestamp=None, end_timestamp=None):
return jhhalchemy.model.time_order.get_by_range(
jhhuser.models.location.Location,
uid,
start_timestamp=start_timestamp,
end_timestamp=end_timestamp)
The jhhalchemy.migrate
module provides some utility functions to obtain database locks and safely run an
Alembic upgrade:
jhhalchemy.migrate.upgrade(
'my_database',
'mysql://root:[email protected]/my_database',
'alembic.ini')
Check out how the fixtures are created in tests/integration/conftest.py.
jhhalchemy includes unit and integration tests. Use pytest to run them. For the
integration tests, you will need to set the MYSQL_CONNECTION_URI
environment variable. You can find more details in
the fixtures.