SQLAlchemy TypeDecorator不起作用 [英] SQLAlchemy TypeDecorator doesn't work

查看:91
本文介绍了SQLAlchemy TypeDecorator不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using xml in my postgresql database and I need a custom type could handle xml data in SQLAlchemy.

所以我制作了 XMLType 类与 xml.etree ,但是它并没有按我希望的那样工作。

So I made XMLType class communicating with xml.etree, but It doesn't work as I wished.

这是我编写的代码:

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 对象):

It works well on retrieving values and result processing. but when I tried to insert a row, I get an error(of course, I put the body as xml.etree.ElementTree.Element object):

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 ,显然绑定处理器不能正常工作,但是我想我已经正确实现了,所以我不知道该怎么做才能改变这种情况。

Seeing that the body value is None, it's obvious that the binding processor do not work right, but I think I implemented that properly so I don't know what should I do to change the situation.

process_bind_param 给了我同样的错误。

我的代码在哪里出错了?

Where did I go wrong in my code?

推荐答案

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

ElementTree.dump() function dumps XML to stream (stdout by default) and returns None. Use ElementTree.tostring() or dump it to StringIO object.

这篇关于SQLAlchemy TypeDecorator不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆