Geração de Slug em Python: Guia Django, Flask e Python Vanilla

Aprenda todos os métodos de geração de slug URL em Python. Crie URLs SEO-friendly com Django slugify, biblioteca python-slugify e funções personalizadas.

O que é um Slug em Python e por que importa?

Um slug é a parte legível e SEO-friendly de uma URL. Criar slugs em Python é crítico para otimização de motores de busca.

Método 1: Slug com 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("Olá Mundo!")
print(slug)  # ola-mundo

Método 3: slugify do Django

from django.utils.text import slugify
slug = slugify("Olá Mundo")
print(slug)  # ola-mundo

Caracteres portugueses

def portuguese_slugify(text):
    pt_map = {'ã': 'a', 'õ': 'o', 'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u', 'ç': 'c'}
    for pt_char, en_char in pt_map.items():
        text = text.replace(pt_char, en_char)
    text = text.lower()
    text = re.sub(r'[^a-z0-9]+', '-', text)
    return text.strip('-')

Conclusão

Python oferece múltiplos métodos para criar slugs. Escolha o adequado para seu projeto.