Faker伪数据生成
版本信息:
Faker==3.0.0
factory-boy==2.12.0
provider:
# encoding=utf-8
import random
from faker.providers import BaseProvider
class NumProvider(BaseProvider):
def num(self):
# ri = self.randomInt()
# return str(ri())
return '123aaaaa'
def randomInt(self):
return lambda a=1, b=30: random.randint(a, b)
def randomStr18(self, num):
ri = lambda a=0, b=9: random.randint(a, b)
s = ''
for i in range(18):
s = s + str(ri())
return s
# encoding=utf-8 import factory from factory import fuzzy from NumProvider import NumProvider class User: def __init__(self, name, num, age, school, city, phone): self.name, self.num, self.age, self.school, self.city, self.phone = \ name, num, age, school, city, phone class School: def __init__(self, schoolName): self.schoolName = schoolName factory.Faker.add_provider(NumProvider) # 添加自定义的NumProvider class SchoolFactory(factory.Factory): class Meta: model = School # schoolName = factory.sequence(lambda n: 'school%04d' % n) # factory.sequence # schoolName = factory.Faker._get_faker().random_int() #调用生成好的provider schoolName = factory.Faker('num').generate() #调用生成好的provider class UserFactory(factory.Factory): class Meta: model = User name = factory.Faker("name", locale="zh_CN") # factory.Faker num = factory.Faker("num") #调用生成好的provider age = factory.fuzzy.FuzzyInteger(42) # factory.fuzzy.FuzzyInteger city = factory.Faker("address", locale="zh_CN") phone = factory.fuzzy.FuzzyText("138", 7, "1", "1234567890") # factory.fuzzy.FuzzyText school = factory.SubFactory(SchoolFactory) # factory.SubFactory class Params: shipped = factory.Trait( name=None ) if __name__ == "__main__": # 单个生成 # seq = [] # seq2=[] # uf = UserFactory() # # print(uf.__dict__) # seq.append(uf.__dict__) # seq2.append(UserFactory().__dict__) # print(seq) # print(seq2) # ##批量生成 # list = [] # fss = factory.build_batch(UserFactory, 4) # for fs in fss: # list.append(fs.__dict__) # print(list) ##部分字段修改 # uff = UserFactory(shipped=True) uff = UserFactory(shipped=False) print(uff.school.__dict__) print(uff.__dict__) print(uff.__dir__())