<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def lock_instance(cls, instance_or_pk, read=False):
 """Return a locked model instance in ``db.session``. :param instance_or_pk: An instance of this model class, or a primary key. A composite primary key can be passed as a tuple. :param read: If `True`, a reading lock is obtained instead of a writing lock. """


        mapper = inspect(cls)
        pk_attrs = [mapper.get_property_by_column(c).class_attribute for c in mapper.primary_key]
        pk_values = cls.get_pk_values(instance_or_pk)
        clause = and_(*[attr == value for attr, value in zip(pk_attrs, pk_values)])
        return cls.query.filter(clause).with_for_update(read=read).one_or_none()