Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy TypeDecorator doesn't work

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?

like image 925
yoloseem Avatar asked Dec 16 '11 07:12

yoloseem


1 Answers

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

like image 66
Denis Otkidach Avatar answered Oct 31 '22 21:10

Denis Otkidach