SQLAlchemy TypeDecorator doesn't work

不打扰是莪最后的温柔 提交于 2019-12-10 13:55:42

问题


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

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

here`s the code that I wrote:

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

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}

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 gives me the same error.

Where did I go wrong in my code?


回答1:


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



来源:https://stackoverflow.com/questions/8530858/sqlalchemy-typedecorator-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!