如何使用SQL Alchemy和SQL Alchemy Utils URLType使其只保存主机名?

2024-05-18 14:22:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在一个项目中使用SQL Alchemy和SQL Alchemy UtilsURLType,我一直在尝试解决如何清理SQLAlchemy属性的输入,以便数据库中存储的唯一对象是furl对象的主机。目前我已经解决了这个问题,只需在每个set操作之前调用一个class方法,如下所示:

class Website(Base, Timestamp):
    __tablename__ = "websites"

    id = Column(Integer, primary_key=True)

    # Data
    origin = Column(URLType, nullable=False, unique=True)

    # Functions
    @classmethod
    def prep_url(cls, url):
        return url.origin

x = furl('https://stackoverflow.com/questions/ask')
ws = Website(origin=Website.prep_url(x))
>>> ws.origin
stackoverflow.com

我希望能像这样使用它:

ws = Website(origin=x)
>>> ws.origin
stackoverflow.com

我想也许this answer就是我要找的,但是我找不到它的文档


Tags: 项目对象comtrueurlsqlwscolumn
1条回答
网友
1楼 · 发布于 2024-05-18 14:22:02

property/setter怎么样

class Website(Base, Timestamp):
    __tablename__ = "websites"

    id = Column(Integer, primary_key=True)

    # Data
    origin_ = Column("origin", URLType, nullable=False, unique=True)

    @property
    def origin(self):
        return self.origin_

    @origin.setter
    def origin(self, url):
        self.origin_ = url.origin

x = furl('https://stackoverflow.com/questions/ask')
ws = Website(origin=x)
>>> ws.origin
stackoverflow.com

相关问题 更多 >

    热门问题