验证SQLAlchemy字段

时间:2015-07-24 16:30:27

标签: python mysql sqlalchemy

我有一个字典,它是从一个看起来像

的程序过程创建的

{'field1: 3, 'field2: 'TEST'}

我将此词典作为其字段(例如:Model(**dict)

提供给模型

我想运行一系列单元测试来确定字段是否是有效的数据类型。

如何验证这些数据类型对我的数据库是否有效而无需进行插入和回滚,因为这会在我的测试中引入片状,因为我会与实际数据库进行正确的交互? (MySQL的)。

2 个答案:

答案 0 :(得分:1)

我对sqlalchemy没有多少经验,但如果你在模型的列中使用数据类型,那会不会有用?

此链接可能会对您有所帮助:http://docs.sqlalchemy.org/en/rel_0_9/core/type_basics.html

答案 1 :(得分:1)

这是一个基本的方式来做你所要求的

class Sample_Table(Base):
    __tablename__ = 'Sample_Table'
    __table_args__ = {'sqlite_autoincrement': True}
    id = Column(Integer, primary_key=True, nullable=False)
    col1 = Column(Integer)
    col2 = Column(Integer)

    def __init__(self, **kwargs):
        for k,v in kwargs.items():
            col_type = str(self.__table__.c[k].type)
            try:            
                if str(type(v).__name__) in col_type.lower():
                    setattr(self, k, v)
                else:
                    raise Exception("BAD COLUMN TYPE FOR COL " + k)
            except ValueError as e:
                print e.message

如果您尝试使用上述内容插入一个列类型与您指定的列不同的记录,则会抛出错误,即它不会执行插入和回滚。

要证明这是有效的,请尝试以下完整代码:

from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class Sample_Table(Base):
    __tablename__ = 'Sample_Table'
    __table_args__ = {'sqlite_autoincrement': True}
    id = Column(Integer, primary_key=True, nullable=False)
    col1 = Column(Integer)
    col2 = Column(Integer)

    def __init__(self, **kwargs):
        for k,v in kwargs.items():
            col_type = str(self.__table__.c[k].type)
            try:            
                if str(type(v).__name__) in col_type.lower():
                    setattr(self, k, v)
                else:
                    raise Exception("BAD COLUMN TYPE FOR COL " + k)
            except ValueError as e:
                print e.message


engine = create_engine('sqlite:///')
session = sessionmaker()
session.configure(bind=engine)
s = session()
Base.metadata.create_all(engine)

data = {"col1" : 1, "col2" : 2}
record = Sample_Table(**data)
s.add(record) #works
s.commit()

data = {"col1" : 1, "col2" : "2"}
record = Sample_Table(**data)
s.add(record) #doesn't work!
s.commit()

s.close()

(即使我使用过SQLite,它也适用于MySQL数据库。)