SQLAlchemy TypeDecorator doesn't work
Asked Answered
F

1

5

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?

Fructidor answered 16/12, 2011 at 7:2 Comment(0)
G
6

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

Gristly answered 16/12, 2011 at 9:54 Comment(2)
Thank you. It was my ignorance, not SQLAlchemy's problem. :-)Fructidor
Oh, I didn't know that there's 'accepted answer' feature. I just did it. Thanks for your consideration.Fructidor

© 2022 - 2024 — McMap. All rights reserved.