利用Factory-boy和sqlalchemy来批量生成数据库表数据

时间:2021-11-16 12:04:52

测试过程中免不了要构造测试数据,如果是单条数据,还比较简单,但如果是批量数据,就比较麻烦了。

最近看到Factory_boy这个python第三方库,它通过SQLAlchemyModelFactory类支持了SQLAlchemy模型,简单的尝试了一下,感觉还挺好用的。

依赖包:

factory-boy==2.12.0
sqlalchemy==1.3.7
mysql-connector-python==8.0.17

user表(mysql):

 CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';

boytest.py

 from sqlalchemy import Column,String, Integer, Unicode, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker Base = declarative_base() class User(Base):
# 表的名字:
__tablename__ = 'user' # 表的结构:
id = Column(String(20), primary_key=True)
name = Column(String(20)) engine = create_engine('mysql+mysqlconnector://autotest:autotest@192.168.1.3:3306/testdb')
DBSession = scoped_session(sessionmaker(bind=engine))#这里需要使用scoped_session #Base.metadata.create_all(engine) #创建表 import factory class UserFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = User
sqlalchemy_session = DBSession # the SQLAlchemy session object
sqlalchemy_session_persistence="commit" #"commit"--perform a session commit() #'flush'-- perform a session flush() id = factory.Sequence(lambda n: n)
#id = 9
name = factory.Sequence(lambda n: u'User %d' % n) #清除表内容
DBSession.query(User).delete()
#DBSession.query(User).filter(User.id==0).delete()
DBSession.commit() # users=DBSession.query(User).all()
# for usr in users:
# print(usr.__dict__) #创建一条记录
UserFactory()
# UserFactory()
#创建100条记录
factory.build_batch(UserFactory, 100)
#DBSession.commit()
users=DBSession.query(User).all()
for usr in users:
print(usr.__dict__)
print(len(users))
DBSession.remove()

结果:
利用Factory-boy和sqlalchemy来批量生成数据库表数据

factory.build_batch(UserFactory, 100)这行代码就实现了100条记录的插入,还是很方便的。

参考内容:
https://www.cnblogs.com/wangtaobiu/p/11007547.html
https://blog.csdn.net/zhyh1435589631/article/details/51549944
https://www.liaoxuefeng.com/wiki/897692888725344/955081460091040
https://factoryboy.readthedocs.io/en/latest/orms.html#sqlalchemy