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?
ElementTree.dump() function dumps XML to stream (stdout by default) and returns None. Use ElementTree.tostring() or dump it to StringIO object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With