Faker es una librería de Python que genera datos falsos pero realistas como nombres, emails, direcciones, números de teléfono, textos y mucho más. Es perfecta para testing, desarrollo y poblar bases de datos con información de prueba.
pip install faker Veamos cómo integrar Faker en una aplicación Flask para generar diferentes tipos de datos:
from flask import Flask, jsonify
from faker import Faker
import random
app = Flask(__name__)
fake = Faker('es_ES') # Configurar para español de España
# También puedes usar múltiples locales
# fake = Faker(['es_ES', 'es_MX', 'es_CO'])
@app.route("/usuario_falso")
def generar_usuario():
usuario = {
"id": fake.random_int(min=1, max=10000),
"nombre": fake.first_name(),
"apellido": fake.last_name(),
"email": fake.email(),
"telefono": fake.phone_number(),
"direccion": {
"calle": fake.street_address(),
"ciudad": fake.city(),
"codigo_postal": fake.postcode(),
"pais": fake.country()
},
"fecha_nacimiento": fake.date_of_birth(minimum_age=18, maximum_age=80).isoformat(),
"trabajo": fake.job(),
"empresa": fake.company(),
"biografia": fake.text(max_nb_chars=200)
}
return jsonify(usuario)
if __name__ == "__main__":
app.run(debug=True) Creemos un endpoint que genere una lista de usuarios falsos:
@app.route("/usuarios/<int:cantidad>")
def generar_usuarios(cantidad):
# Limitar la cantidad para evitar sobrecarga
if cantidad > 100:
cantidad = 100
usuarios = []
for _ in range(cantidad):
usuario = {
"id": fake.uuid4(),
"nombre_completo": fake.name(),
"username": fake.user_name(),
"email": fake.email(),
"avatar": fake.image_url(width=200, height=200),
"direccion_completa": fake.address(),
"fecha_registro": fake.date_time_between(start_date='-2y', end_date='now').isoformat(),
"activo": fake.boolean(chance_of_getting_true=80),
"salario": fake.random_int(min=30000, max=120000)
}
usuarios.append(usuario)
return jsonify({
"total": len(usuarios),
"usuarios": usuarios
}) Ejemplo práctico para generar productos falsos de una tienda online:
@app.route("/productos/<int:cantidad>")
def generar_productos(cantidad):
if cantidad > 50:
cantidad = 50
categorias = ['Electrónicos', 'Ropa', 'Hogar', 'Deportes', 'Libros', 'Juguetes']
productos = []
for _ in range(cantidad):
producto = {
"id": fake.uuid4(),
"nombre": fake.catch_phrase(),
"descripcion": fake.text(max_nb_chars=300),
"precio": round(fake.random.uniform(10.99, 999.99), 2),
"categoria": fake.random_element(elements=categorias),
"marca": fake.company(),
"codigo_barras": fake.ean13(),
"peso": f"{fake.random.uniform(0.1, 5.0):.2f} kg",
"dimensiones": {
"largo": fake.random_int(min=5, max=50),
"ancho": fake.random_int(min=5, max=30),
"alto": fake.random_int(min=2, max=20)
},
"stock": fake.random_int(min=0, max=100),
"imagen": fake.image_url(width=400, height=400),
"fecha_creacion": fake.date_time_between(start_date='-1y', end_date='now').isoformat(),
"disponible": fake.boolean(chance_of_getting_true=90)
}
productos.append(producto)
return jsonify({
"total": len(productos),
"productos": productos
}) Generemos posts falsos para una red social:
@app.route("/posts/<int:cantidad>")
def generar_posts(cantidad):
if cantidad > 30:
cantidad = 30
posts = []
for _ in range(cantidad):
post = {
"id": fake.uuid4(),
"autor": {
"nombre": fake.name(),
"username": fake.user_name(),
"avatar": fake.image_url(width=100, height=100)
},
"contenido": fake.paragraph(nb_sentences=fake.random_int(min=1, max=5)),
"hashtags": [f"#{fake.word()}" for _ in range(fake.random_int(min=0, max=5))],
"likes": fake.random_int(min=0, max=1000),
"comentarios": fake.random_int(min=0, max=50),
"compartidos": fake.random_int(min=0, max=100),
"fecha_publicacion": fake.date_time_between(start_date='-30d', end_date='now').isoformat(),
"ubicacion": {
"ciudad": fake.city(),
"coordenadas": {
"lat": float(fake.latitude()),
"lng": float(fake.longitude())
}
},
"imagen": fake.image_url(width=600, height=400) if fake.boolean(chance_of_getting_true=60) else None
}
posts.append(post)
return jsonify({
"total": len(posts),
"posts": posts
}) Datos personales: name(), first_name(), last_name(), email(), phone_number()
Direcciones: address(), street_address(), city(), country(), postcode()
Fechas: date(), date_time(), date_of_birth(), future_date()
Texto: text(), paragraph(), sentence(), word(), catch_phrase()
Internet: url(), domain_name(), ipv4(), user_name(), password()
Números: random_int(), random_digit(), random_number()
Otros: uuid4(), boolean(), color_name(), file_name()
Faker soporta múltiples idiomas y regiones:
# Diferentes configuraciones de idioma
fake_es = Faker('es_ES') # Español de España
fake_mx = Faker('es_MX') # Español de México
fake_ar = Faker('es_AR') # Español de Argentina
fake_en = Faker('en_US') # Inglés de Estados Unidos
@app.route("/nombres_por_pais")
def nombres_por_pais():
return jsonify({
"españa": fake_es.name(),
"mexico": fake_mx.name(),
"argentina": fake_ar.name(),
"estados_unidos": fake_en.name()
}) Usa semillas para generar los mismos datos en cada ejecución (útil para testing):
@app.route("/datos_consistentes")
def datos_consistentes():
# Establecer semilla para resultados reproducibles
Faker.seed(12345)
fake_consistente = Faker('es_ES')
# Estos datos serán siempre los mismos
return jsonify({
"usuario1": fake_consistente.name(),
"usuario2": fake_consistente.name(),
"email1": fake_consistente.email(),
"email2": fake_consistente.email()
}) app.pypip install faker flaskpython app.pyhttp://localhost:5000/usuario_falsohttp://localhost:5000/usuarios/10http://localhost:5000/productos/5http://localhost:5000/posts/3