Lafada Lafada - 27 days ago 16
Python Question

how to create read only model for cassandra

I have cassandra model

from cassandra.cqlengine import columns
from cassandra.cqlengine.models import Model

class StudentModules(Model):
"""Model for Student get."""

__table_name__ = 'students'
student_id = columns.UUID(primary_key=True, default=uuid4)
student_name = columns.Text(index=True)


In my case, table
students
already exists, and I always want to use this module for
select
query.

I tried
__abstract__
attribute, but in this case, I am not able to call
filter
or
get
call for model.

Answer

There's not a built-in way to do this. You could get behavior like that by defining an intermediate class and overriding the mutation methods*:

class ROModel(Model):
    __abstract__=True

    @classmethod
    def create(cls, **_):
        raise NotImplementedError()

    def save(self):
        raise NotImplementedError()

    def update(self, **_):
        raise NotImplementedError()

    def delete(self):
        raise NotImplementedError()

class Test(ROModel):
    __keyspace__='test'
    k = columns.Integer(primary_key=True)
    a = columns.Integer()
    b = columns.Integer()

print Test.objects.first()
Test(k=1, b=4).update()  # NotImplementedError
Test.create(k=1, a=2, b=3)  # NotImplementedError
Test(k=1).delete()  # NotImplementedError
Test(k=1, a=3).save()  # NotImplementedError

* note that this is only a partial solution -- you would also need to update ROModel.__queryset__ with a similarly specialized query.ModelQuerySet.

However, I'm having trouble understanding what this buys you. Any solution making the thing read-only will result in a runtime error if you call a mutating method.

In any case, you might also be better off using auth and a user/role with only select permissions. https://cassandra.apache.org/doc/latest/cql/security.html#data-control