SQLAlchemy TypeDecorator 不起作用
我在 postgresql 数据库中使用 xml
,并且需要一个自定义类型可以处理 SQLAlchemy 中的 xml
数据。
所以我制作了 XMLType
类与 xml.etree
进行通信,但它并没有按照我的意愿工作。
这是我编写的代码:
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
它在检索值和结果处理方面效果很好。但是当我尝试插入一行时,出现错误(当然,我将 body
作为 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}
: code>body 值为 None
,很明显绑定处理器无法正常工作,但我认为我正确实现了它,所以我不知道应该做什么来改变这种情况。
process_bind_param
给了我同样的错误。
我的代码哪里出错了?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ElementTree.dump()
函数将 XML 转储到流(默认为 stdout)并返回None
。使用 ElementTree.tostring() 或将其转储到 StringIO 对象。ElementTree.dump()
function dumps XML to stream (stdout by default) and returnsNone
. UseElementTree.tostring()
or dump it toStringIO
object.