Search code examples
pythontornado-motor

Dynamic initialisation of DB in constructor


I am using motor with tornado. I have the following class:

class N():
      def __init__(self,collectionName host='localhost', port=27017):
      self.con=motor.MotorClient(host,port)
      self.xDb=self.con.XDb
      setattr(self,collectionName,self.xDb[collectionName])

This is actually a parent class that i want to extend. The child class will call this class' init to set the collectionName. The problem is I also have some other methods in this class E.g.

   @tornado.gen.coroutine
   def dropDB(self):
      yield self.xDb.drop_collection(self.COLLECTION??)

The above is broken because I dynamically set the collection in the init what's a way I can determine the self. variable I set to use in the base methods?


Solution

  • Set another variable:

    class N():
        def __init__(self, collectionName, host='localhost', port=27017):
            # ... your existing code ...
            self.collectionName = collectionName
    
       @tornado.gen.coroutine
       def dropDB(self):
          yield self.xDb.drop_collection(self.collectionName)
    

    Since drop_collection takes a name or a MotorCollection object, there are other ways you could store this data on self, but the way I showed might be the easiest.

    http://motor.readthedocs.io/en/stable/api/motor_database.html#motor.motor_tornado.MotorDatabase.drop_collection