SQLAlchemy TypeDecorator不起作用

yol*_*eem 5 xml postgresql sqlalchemy elementtree

xml在我的postgresql数据库中使用,我需要一个自定义类型可以处理xmlSQLAlchemy中的数据.

所以我让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
Run Code Online (Sandbox Code Playgroud)

它适用于检索值和结果处理.但是当我试图插入一行时,我得到一个错误(当然,我把bodyas 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}
Run Code Online (Sandbox Code Playgroud)

看到body值是None,很明显绑定处理器不能正常工作,但我认为我已正确实现,所以我不知道如何改变这种情况.

process_bind_param 给了我同样的错误.

我的代码在哪里出错了?

Den*_*ach 5

ElementTree.dump()函数将XML转储为流(默认情况下为stdout)并返回None.使用ElementTree.tostring()或转储到StringIO对象.