cqlengine multilpe keyspaces

2019-06-02 07:20发布

问题:

I am using cassandra from python 3.4.0 with cassandra-driver 2.5.0 (and cqlengine models) .

App data are distributed in: one keyspace for management and one keyspace per user. i need to query two keyspaces: master+custom.

I have coded a tiny class for keyspace switching used like this:

with keyspace(new_keyspace):
    #do stuff with new_keyspace
#do stuff with previous keyspace

My first version was:

class keyspace(object):

    def __init__(self, new_keyspace):
        self.new_keyspace = new_keyspace
        self.old_keyspace = get_session().keyspace

    def __enter__(self):
        session = get_session()
        session.set_keyspace()
        connection.set_session(session)

    def __exit__(self, type, value, traceback):
        session = get_session()
        session.set_keyspace(self.old_keyspace)
        connection.set_session(session)        

And does not work at all. I have recoded class with:

class keyspace(object):

    def __init__(self, new_keyspace):
        self.new_keyspace = new_keyspace
        self.old_keyspace = cassandra.cqlengine.models.DEFAULT_KEYSPACE

    def __enter__(self):
        cassandra.cqlengine.models.DEFAULT_KEYSPACE = self.new_keyspace

    def __exit__(self, type, value, traceback):
        cassandra.cqlengine.models.DEFAULT_KEYSPACE = self.old_keyspace

Last code works, but i feel insecure when use DEFAULT_KEYSPACE.

Why get_session(), set_session has no effect?

is cassandra.cqlengine.models.DEFAULT_KEYSPACE safe for check this?

Thanks

回答1:

The question is old, hope this helps someone else.

Yes the second approach is correct. get_session() and set_session() has no effect because it checks if models.DEFAULT_KEYSPACE is set and only sets the new keyspace if it is not set. So to effectively change the keyspace you need to change models.DEFAULT_KEYSPACE