Using postgresql xml data type with sqlalchemy
postgresql-9.2, python, sqlalchemy, xml
Solution
If you need to have native 'xml' data type in postgresql database, you need to write custom type which inherited from UserDefinedType not from TypeDecorator. Documentation
Here is what I used in one of the projects:
import xml.etree.ElementTree as etree
import sqlalchemy
class XMLType(sqlalchemy.types.UserDefinedType):
def get_col_spec(self):
return 'XML'
def bind_processor(self, dialect):
def process(value):
if value is not None:
if isinstance(value, str):
return value
else:
return etree.tostring(value)
else:
return None
return process
def result_processor(self, dialect, coltype):
def process(value):
if value is not None:
value = etree.fromstring(value)
return value
return process
Problem
SqlAlchemy supports most database specific data types via dialects, but I could not find anything to work with the postgresql xml column type. Does somebody know a working solution. Idealy it should not require a custom column type implementation by myself.