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

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

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

 

依赖包:

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

 

user表(mysql):

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

 

 boytest.py

 1 from sqlalchemy import Column,String, Integer, Unicode, create_engine
 2 from sqlalchemy.ext.declarative import declarative_base
 3 from sqlalchemy.orm import scoped_session, sessionmaker
 4 
 5 Base = declarative_base()
 6 
 7 class User(Base):
 8     # 表的名字:
 9     __tablename__ = 'user'
10 
11     # 表的结构:
12     id = Column(String(20), primary_key=True)
13     name = Column(String(20))
14 
15 engine = create_engine('mysql+mysqlconnector://autotest:autotest@192.168.1.3:3306/testdb')
16 DBSession = scoped_session(sessionmaker(bind=engine))#这里需要使用scoped_session
17 
18 #Base.metadata.create_all(engine) #创建表
19 
20 import factory
21 
22 class UserFactory(factory.alchemy.SQLAlchemyModelFactory):
23     class Meta:
24         model = User
25         sqlalchemy_session = DBSession   # the SQLAlchemy session object
26         sqlalchemy_session_persistence="commit" #"commit"--perform a session commit() #'flush'-- perform a session flush()
27 
28     id = factory.Sequence(lambda n: n)
29     #id = 9
30     name = factory.Sequence(lambda n: u'User %d' % n)
31 
32 #清除表内容
33 DBSession.query(User).delete()
34 #DBSession.query(User).filter(User.id==0).delete()
35 DBSession.commit()
36 
37 
38 # users=DBSession.query(User).all()
39 # for usr in users:
40 #     print(usr.__dict__)
41 
42 #创建一条记录
43 UserFactory()
44 # UserFactory()
45 #创建100条记录
46 factory.build_batch(UserFactory, 100)
47 #DBSession.commit()
48 users=DBSession.query(User).all()
49 for usr in users:
50     print(usr.__dict__)
51 print(len(users))
52 DBSession.remove()

 

结果:

 

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

posted @ 2019-08-17 21:46  月色深潭  阅读(824)  评论(1编辑  收藏  举报