SQLAlchemy TypeDecorator not working

I use xml in my postgresql database and I need the user type to process the xml data in SQLAlchemy.

So, I created an XMLType class that communicates with xml.etree , but it does not work as I wanted.

here is the code 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 in extracting values ​​and processing results. but when I tried to insert the line, I get an error message (of course, I put the body object as xml.etree.ElementTree.Element ):

 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 is obvious that the binding handler is not working correctly, but I think I implemented it correctly, so I don’t know what to do to change the situation.

process_bind_param gives me the same error.

Where am I wrong in my code?

+4
source share
1 answer

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

+4
source

Source: https://habr.com/ru/post/1386653/


All Articles