Generación de Slug en Python: Guía para Django, Flask y Python Vanilla
Aprende todos los métodos de generación de slug URL en Python. Crea URLs SEO-friendly con Django slugify, biblioteca python-slugify y funciones personalizadas.
¿Qué es un Slug en Python y por qué importa?
Un slug es la parte legible y SEO-friendly de una URL. Crear slugs en Python es crítico para la optimización de motores de búsqueda.
Método 1: Slug con Python Vanilla
import re
import unicodedata
def slugify(text):
text = unicodedata.normalize('NFKD', text)
text = text.encode('ascii', 'ignore').decode('ascii')
text = text.lower()
text = re.sub(r'[^a-z0-9]+', '-', text)
return text.strip('-')Método 2: Biblioteca python-slugify
pip install python-slugify
from slugify import slugify
slug = slugify("¡Hola Mundo!")
print(slug) # hola-mundoMétodo 3: slugify de Django
from django.utils.text import slugify
slug = slugify("Hola Mundo")
print(slug) # hola-mundoCaracteres españoles
def spanish_slugify(text):
es_map = {'ñ': 'n', 'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u'}
for es_char, en_char in es_map.items():
text = text.replace(es_char, en_char)
text = text.lower()
text = re.sub(r'[^a-z0-9]+', '-', text)
return text.strip('-')Conclusión
Python ofrece múltiples métodos para crear slugs. Elija el adecuado para su proyecto.