class TroncalSIPFactory(DjangoModelFactory): class Meta: model = TroncalSIP nombre = Sequence(lambda n: "TroncalSIP{0}".format(n)) canales_maximos = lazy_attribute(lambda a: faker.random_int(1, 10)) caller_id = Sequence(lambda n: "CallID{0}".format(n)) tecnologia = lazy_attribute(lambda a: faker.random_int(0, 1)) text_config = ""
class IdentificadorClienteFactory(DjangoModelFactory): class Meta: model = IdentificadorCliente nombre = Sequence(lambda n: "Identificador cliente {0}".format(n)) url = Sequence(lambda n: "https://url{0}.net".format(n)) tipo_interaccion = lazy_attribute(lambda a: faker.random_int(1, 3)) audio = SubFactory(ArchivoDeAudioFactory) longitud_id_esperado = lazy_attribute(lambda a: faker.random_int(3, 10)) timeout = lazy_attribute(lambda a: faker.random_int(3, 7)) intentos = lazy_attribute(lambda a: faker.random_int(2, 9))
def generate_hotels(db): cursor = db.cursor() for _ in range(1, hotels + 1): insert_random_hotel(cursor) for _ in range(1, buildings + 1): random_floors = faker.random_int(*floors) rooms_per_floor = faker.random_int(*rooms) insert_random_building(cursor, floors=random_floors) for i in range(random_floors): for j in range(1, rooms_per_floor + 1): j = '{0}{1:02d}'.format(i, j) insert_random_room(cursor, floor=i, number=j) db.commit()
def seed_orders(): orders_to_seed = 25 orders_count = Order.objects.all().count() sys.stdout.write('[+] Seeding %d orders\n' % (orders_to_seed - orders_count)) for i in range(orders_count, orders_to_seed): address_id = Address.objects.order_by('?').only('id').first().id user_id = AppUser.objects.order_by('?').values('id').first()['id'] Order.objects.create(address_id=address_id, user_id=user_id) order_items_to_seed = 35 order_items_count = OrderItem.objects.count() sys.stdout.write('[+] Seeding %d order items\n' % (order_items_to_seed - order_items_count)) for i in range(order_items_count, order_items_to_seed): product = Product.objects.order_by('?').only('id').first() order = Order.objects.get_order_not_containing_product(product) if order is None: # all orders have this product already continue OrderItem.objects.create( name=product.name, slug=product.slug, user_id=order.user_id, order_id=order.id, product=product, quantity=faker.random_int(min=1, max=7), price=min(5, product.price + (round(random.uniform(-20.0, 20.0), 2))), # random price near the usual product price # user=AppUser.objects.order_by('?').first()) )
def generate_history(db): cursor = db.cursor() days = history_years * 365 + 30 for i in range(1, hotels_counter + 1): for j in range(int(days / discount_duration)): if faker.random.random() < discounts: insert_random_discount(cursor, j, i, 'hotel') db.commit() for i in range(1, buildings_counter + 1): for j in range(int(days / discount_duration)): if faker.random.random() < discounts: insert_random_discount(cursor, j, i, 'building') db.commit() for i in range(1, rooms_counter + 1): for j in range(int(days / discount_duration)): if faker.random.random() < discounts: insert_random_discount(cursor, j, i, 'room') db.commit() cursor = db.cursor() for i in range(1, rooms_counter + 1): for j in range(int(days / price_duration)): insert_random_price(cursor, j, i) db.commit() cursor = db.cursor() for i in range(1, rooms_counter + 1): for j in range(int(days / reservation_duration)): if faker.random.random() < reservations: insert_random_reservation(cursor, j, i, faker.random_int(1, clients_counter)) db.commit()
def seed_products(): products_count = Product.objects.count() products_to_seed = 35 sys.stdout.write('[+] Seeding %d products\n' % (products_to_seed - products_count)) dir = os.path.join(os.getcwd(), 'static', 'images', 'products') if not os.path.exists(dir): os.makedirs(dir) for i in range(products_count, products_to_seed): name = faker.sentence() # slug = faker.slug() # description = faker.paragraph(nb_sentences=3, variable_nb_sentences=10) description = faker.text() tags = Tag.objects.get_random_tag() categories = Category.objects.gent_random_category() price = round(random.uniform(150, 3000), 2) start_date = datetime.date(year=2016, month=1, day=1) random_date = faker.date_between(start_date=start_date, end_date='+4y') publish_on = random_date # publish_on = faker.date_time_between('-3y', '+1y') product = Product.objects.create(name=name, description=description, price=price, publish_on=publish_on, stock=faker.random_int(min=0, max=400)) product.tags.add(tags) product.categories.add(categories) file_name = "".join(random.choice(ascii_lowercase) for i in range(16)) file_path = os.path.join(dir, file_name) ProductImage.objects.create(file_name=file_name, original_name='adults.png', file_length=faker.random.randint(400, 10000), product=product, file_path=file_path.replace(os.getcwd(), '').replace('\\', '/'))
class RutaSalienteFactory(DjangoModelFactory): class Meta: model = RutaSaliente nombre = Sequence(lambda n: "RutaSaliente{0}".format(n)) ring_time = lazy_attribute(lambda a: faker.random_int(0, 120)) dial_options = ""
class OpcionCalificacionFactory(DjangoModelFactory): class Meta: model = OpcionCalificacion campana = SubFactory(CampanaFactory) tipo = lazy_attribute(lambda a: faker.random_int(0, 1)) nombre = lazy_attribute(lambda a: faker.text(15)) formulario = SubFactory(FormularioFactory)
class AgenteProfileFactory(DjangoModelFactory): class Meta: model = AgenteProfile user = SubFactory(UserFactory) sip_extension = lazy_attribute(lambda a: faker.ean8()) grupo = SubFactory(GrupoFactory) estado = lazy_attribute(lambda a: faker.random_int(1, 3)) reported_by = SubFactory(UserFactory)
class SitioExternoFactory(DjangoModelFactory): class Meta: model = SitioExterno nombre = lazy_attribute(lambda a: faker.text(15)) url = lazy_attribute(lambda a: "http://{0}.com".format(a.nombre.replace(" ", "_"))) disparador = SitioExterno.BOTON metodo = SitioExterno.GET formato = None objetivo = lazy_attribute(lambda a: faker.random_int(1, 2))
class TroncalSIPFactory(DjangoModelFactory): class Meta: model = TroncalSIP nombre = Sequence(lambda n: "TroncalSIP{0}".format(n)) canales_maximos = lazy_attribute(lambda a: faker.random_int(1, 10)) caller_id = Sequence(lambda n: "CallID{0}".format(n)) register_string = Sequence( lambda n: "Register{0}@localhost:11443".format(n)) text_config = ""
class QueueMemberFactory(DjangoModelFactory): class Meta: model = QueueMember member = SubFactory(AgenteProfileFactory) queue_name = SubFactory(QueueFactory) membername = Sequence(lambda n: "membername_{0}.dat".format(n)) interface = Sequence(lambda n: "interface_{0}.dat".format(n)) penalty = lazy_attribute(lambda a: faker.random_int(0, 9)) paused = lazy_attribute(lambda a: faker.random_number(2)) id_campana = lazy_attribute(lambda a: "{0}_campana".format(uuid4()))
class FieldFormularioFactory(DjangoModelFactory): class Meta: model = FieldFormulario formulario = SubFactory(FormularioFactory) nombre_campo = lazy_attribute(lambda a: "campo_{0}".format(uuid4())) # Cuidado al crear con este orden aleatorio orden = lazy_attribute(lambda a: faker.random_int(1, 1000)) tipo = FieldFormulario.TIPO_TEXTO values_select = None is_required = False
class GrabacionFactory(DjangoModelFactory): class Meta: model = Grabacion fecha = lazy_attribute(lambda a: timezone.now()) tipo_llamada = lazy_attribute(lambda a: faker.random_int(1, 3)) id_cliente = lazy_attribute(lambda a: format(uuid4().int)) tel_cliente = lazy_attribute(lambda a: str(faker.random_number(7))) grabacion = lazy_attribute(lambda a: faker.text(max_nb_chars=5)) agente = SubFactory(AgenteProfileFactory) campana = SubFactory(CampanaFactory) callid = lazy_attribute(lambda a: format(uuid4().int))
class LlamadaLogFactory(DjangoModelFactory): class Meta: model = LlamadaLog time = lazy_attribute(lambda a: timezone.now()) callid = lazy_attribute(lambda a: faker.ean8()) campana_id = Sequence(lambda n: n) tipo_campana = lazy_attribute(lambda a: faker.random_int(1, 4)) agente_id = Sequence(lambda n: n) event = Sequence(lambda n: "evento_{0}".format(n)) numero_marcado = lazy_attribute(lambda a: faker.phone_number()) contacto_id = Sequence(lambda n: n) bridge_wait_time = lazy_attribute(lambda a: faker.random_number(3)) duracion_llamada = lazy_attribute(lambda a: faker.random_number(3)) archivo_grabacion = lazy_attribute(lambda a: faker.text(15))
def seed_comments(): comments_count = Comment.objects.count() comments_to_seed = 31 sys.stdout.write('[+] Seeding %d comments\n' % (comments_to_seed - comments_count)) if bool(random.getrandbits(1)): rating = faker.random_int(min=1, max=5) else: rating = None for i in range(comments_count, comments_to_seed): Comment.objects.create(content=faker.sentence(), user_id=AppUser.objects.order_by('?').only('id').first().id, rating=rating, product=Product.objects.order_by('?').only('id').first())
def generate_workbook(cls): col_reference, col_name, col_address, \ col_postal_code, col_city, col_country, \ col_url = range(0, 7) columns = ((col_reference, lambda: faker.random_int(1, 500)), (col_name, lambda: 'Hospital {}'.format(faker.name())), (col_address, lambda: faker.address().replace('\n', '')), (col_postal_code, faker.postalcode), (col_city, faker.city), (col_country, lambda: country.CountryFactory().iso_code), (col_url, faker.url)) workbook = openpyxl.Workbook() worksheet = workbook.active for row in range(1, 11): for column, func in columns: worksheet.cell(row=row, column=column + 1).value = func() return workbook
class CampanaFactory(DjangoModelFactory): class Meta: model = Campana nombre = lazy_attribute(lambda a: "campana_{0}".format(uuid4())) estado = lazy_attribute(lambda a: faker.random_digit_not_null()) fecha_inicio = lazy_attribute(lambda a: timezone.now()) fecha_fin = lazy_attribute(lambda a: a.fecha_inicio) bd_contacto = SubFactory(BaseDatosContactoFactory) tipo_interaccion = Campana.FORMULARIO campaign_id_wombat = lazy_attribute(lambda a: faker.random_number(7)) type = lazy_attribute(lambda a: faker.random_int(1, 3)) sitio_externo = None reported_by = SubFactory(UserFactory) nombre_template = lazy_attribute(lambda a: faker.text(max_nb_chars=6)) @post_generation def supervisors(self, create, extracted, **kwargs): if not create: return if extracted: for supervisor in extracted: self.supervisors.add(supervisor)
faker = faker.Faker(locale='zh_CN') # 将项目根目录添加到python的模块搜索路径中 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') # 启动django, 只有启动了Django,才能使用django的,ORM系统 django.setup() from comment.models import ArticleComment from comment.models import Notification # 清除旧数据 Notification.objects.all().delete() User = get_user_model() sender = User.objects.get(id=2) receiver = User.objects.get(id=1) logger.info('{0} generate fake data at {1}'.format( getpass.getuser(), datetime.datetime.now())) comment = ArticleComment.objects.get(id=13) for _ in range(10): Notification.objects.create(sender=sender, receiver=receiver, comment=comment, create_at=faker.date_time(), status=1, is_read=faker.random_int(0, 1)) print('Done at {0}'.format(datetime.datetime.now()))