【问题标题】:How do you make a declarative_base-derived class conform to an interface?如何使 declarative_base 派生类符合接口?
【发布时间】:2019-01-11 12:56:31
【问题描述】:

我有一张桌子:

CREATE TABLE `windows_files` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `filepath` varchar(260) DEFAULT NULL,
  `timestamp` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
);

我有一个基类:

class File:
    path: str
    modified: datetime.datetime

    def delete(self):
        os.remove(self.path)

我有一个declarative_base-派生类:

Base = declarative_base()

class WindowsFile(File, Base):
    __tablename__ = 'windows_files'
    id = Column(Integer, primary_key=True)
    filepath = Column(String(260))
    timestamp = Column(DateTime)

麻烦的是,WindowsFile不是一个很好的File

>>> file = session.query(WindowsFile).first()
>>> ...
>>> file.delete()
Traceback (most recent call last):
  File "<pyshell#34916>", line 1, in <module>
...
    os.remove(self.path)
AttributeError: 'WindowsFile' object has no attribute 'path'

如何使WindowsFile 适合接口,隐藏其实现细节?我无法更改数据库,因为其他东西正在使用它,并且我无法更改File 的定义,因为windows_files 的列名是非常特定于实现的。

【问题讨论】:

    标签: python interface sqlalchemy multiple-inheritance


    【解决方案1】:

    您可以通过将列名作为第一个参数传递给Column 构造函数,将列名与其属性名分开命名,因此WindowsFile 既可以实现接口又可以反映表:

    class WindowsFile(File, Base):
        __tablename__ = 'windows_files'
        id = Column(Integer, primary_key=True)
        path = Column('filepath', String(260))
        modified = Column('timestamp', DateTime)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 2019-11-05
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 2010-12-19
      相关资源
      最近更新 更多