SQLAlchemy在MSSQL中声明XML的自定义UserDefinedType

时间:2017-04-10 21:47:49

标签: python sql-server sqlalchemy

我正在尝试声明一个自定义类型的" XMLType"用于MSSQL。但我一直在'AttributeError: module 'app.db.XMLType' has no attribute '_set_parent_with_dispatch''。我没有在XMLType类文件中看到任何未正确声明的内容。

import sqlalchemy.types as types

from lxml import etree

class XMLType(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

我的代码基于http://docs.sqlalchemy.org/en/latest/core/custom_types.html?highlight=get_col_spec#sqlalchemy.types.UserDefinedTypeUsing postgresql xml data type with sqlalchemy

1 个答案:

答案 0 :(得分:0)

所以导入时碰巧出了问题。对于我的模型,我最初有以下内容:

from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
import conductor.db.XMLType as XML

Base = declarative_base()

class Raw_data_records(Base):
    __tablename__ = 'raw_data_records'

    id = Column('id', Integer, primary_key=True, autoincrement=True)
    basename = Column('basename', String)
    filename = Column('filename', String)
    file_size = Column('file_size', Integer)
    machine = Column('machine', String)
    insert_timestamp = Column('insert_timestamp', DateTime)
    raw_xml = Column('raw_xml', XML)

然后我将导入更改为:

from spcconductor.db.XMLType import XMLTyperaw_xml = Column('raw_xml', XML)raw_xml = Column('raw_xml', XMLType)并且有效。

对于任何需要这些信息的人来说,这是XMLType.py(我还没有测试过......):

import sqlalchemy.types as types

from lxml import etree

class XMLType(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