【问题标题】:SQLAlchemy TypeDecorator doesn't workSQLAlchemy TypeDecorator 不起作用
【发布时间】:2011-12-16 07:02:41
【问题描述】:

我在我的 postgresql 数据库中使用xml,我需要一个自定义类型来处理 SQLAlchemy 中的xml 数据。

所以我让XMLType 类与xml.etree 通信,但它没有按我的意愿工作。

这是我写的代码:

import xml.etree.ElementTree as etree

class XMLType(sqlalchemy.types.TypeDecorator):

    impl = sqlalchemy.types.UnicodeText
    type = etree.Element

    def get_col_spec(self):
        return 'xml'

    def bind_processor(self, dialect):
        def process(value):
            if value is not None:
                return etree.dump(value)
            else:
                return None
        return process

    def process_result_value(self, value, dialect):
        if value is not None:
            value = etree.fromstring(value)
        return value

它在检索值和结果处理方面效果很好。但是当我尝试插入一行时,我得到一个错误(当然,我把body作为xml.etree.ElementTree.Element对象):

IntegrityError: (IntegrityError) null value in column "body" violates not-null 
constraint "INSERT INTO comments (id, author_id, look_id, body, created_at) 
VALUES (nextval('object_seq'), %(author_id)s, %(look_id)s, %(body)s, now()) 
RETURNING comments.id" {'body': None, 'author_id': 1550L, 'look_id': 83293L}

看到body 的值是None,很明显绑定处理器不能正常工作,但我认为我正确地实现了,所以我不知道该怎么做才能改变这种情况。

process_bind_param 给了我同样的错误。

我的代码哪里出错了?

【问题讨论】:

    标签: xml postgresql sqlalchemy elementtree


    【解决方案1】:

    ElementTree.dump() 函数将 XML 转储到流(默认为标准输出)并返回 None。使用ElementTree.tostring() 或将其转储到StringIO 对象。

    【讨论】:

    • 谢谢。这是我的无知,而不是 SQLAlchemy 的问题。 :-)
    • 哦,我不知道有“接受答案”功能。我刚刚做完。感谢您的考虑。
    猜你喜欢
    • 1970-01-01
    • 2015-03-04
    • 2016-04-18
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多