【问题标题】:Dynamic initialisation of DB in constructor在构造函数中动态初始化 DB
【发布时间】:2016-06-25 09:28:08
【问题描述】:

我正在使用带龙卷风的马达。我有以下课程:

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])

这实际上是我想要扩展的父类。子类会调用这个类的init来设置collectionName。问题是我在这个类中还有一些其他方法,例如

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

上面是坏的,因为我在 init 中动态设置了集合,这是我可以确定自我的一种方式。我设置为在基本方法中使用的变量?

【问题讨论】:

    标签: python tornado-motor


    【解决方案1】:

    设置另一个变量:

    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)
    

    由于 drop_collection 采用名称或 MotorCollection 对象,因此您可以通过其他方式将这些数据存储在 self 上,但我展示的方式可能是最简单的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 2018-08-02
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多