加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml – SQLAlchemy TypeDecorator不起作用

发布时间:2020-12-16 23:11:21 所属栏目:百科 来源:网络整理
导读:我在我的 postgresql数据库中使用xml,我需要一个自定义类型来处理SQLAlchemy中的xml数据. 所以我让XMLType类与xml.etree进行通信,但它并不像我希望的那样工作. 这是我写的代码: import xml.etree.ElementTree as etreeclass XMLType(sqlalchemy.types.TypeD
我在我的 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

它适用于检索值和结果处理.但是当我尝试插入一行时,我得到一个错误(当然,我把主体设置为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}

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

process_bind_param给了我同样的错误.

我的代码在哪里出错了?

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读