【问题标题】:Validating SQLAlchemy Fields验证 SQLAlchemy 字段
【发布时间】:2015-07-24 16:30:26
【问题描述】:

我有一个字典,它是从一个看起来像这样的程序过程创建的

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

我将此字典作为其字段输入到模型中(例如:Model(**dict)

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

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

【问题讨论】:

标签: python mysql sqlalchemy


【解决方案1】:

我对 sqlalchemy 没有太多经验,但是如果您在模型的列中使用数据类型,那会不会起作用?

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

【讨论】:

    【解决方案2】:

    这是按照您的要求进行操作的基本方法

    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 数据库。)

    【讨论】:

    • @Andy,这就是你要找的吗?如果是,请将答案标记为已接受;如果不是,请澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多