在SQLAlchemy中使用Postgresql xml数据类型 [英] Using postgresql xml data type with sqlalchemy

查看:181
本文介绍了在SQLAlchemy中使用Postgresql xml数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SqlAlchemy通过方言支持大多数特定于数据库的数据类型,但是我找不到与postgresql xml列类型一起使用的任何东西。有人知道可行的解决方案吗?理想情况下,它不需要我自己执行自定义列类型。

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.

推荐答案

如果需要使用 native'xml'数据类型在Postgresql数据库中,您需要编写自 UserDefinedType 而不是从TypeDecorator继承的自定义类型。 文档

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

这篇关于在SQLAlchemy中使用Postgresql xml数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆