Génération de Slug en Python : Guide Django, Flask et Python Vanilla

Apprenez toutes les méthodes de génération de slug URL en Python. Créez des URLs SEO-friendly avec Django slugify, la bibliothèque python-slugify et des fonctions personnalisées.

Qu'est-ce qu'un Slug en Python et pourquoi est-ce important?

Un slug est la partie lisible et SEO-friendly d'une URL. Créer des slugs en Python est crucial pour l'optimisation des moteurs de recherche.

Méthode 1: Slug avec 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éthode 2: Bibliothèque python-slugify

pip install python-slugify

from slugify import slugify
slug = slugify("Bonjour le Monde!")
print(slug)  # bonjour-le-monde

Méthode 3: slugify de Django

from django.utils.text import slugify
slug = slugify("Bonjour le Monde")
print(slug)  # bonjour-le-monde

Caractères français

def french_slugify(text):
    fr_map = {'é': 'e', 'è': 'e', 'ê': 'e', 'à': 'a', 'â': 'a', 'ç': 'c', 'ù': 'u', 'û': 'u'}
    for fr_char, en_char in fr_map.items():
        text = text.replace(fr_char, en_char)
    text = text.lower()
    text = re.sub(r'[^a-z0-9]+', '-', text)
    return text.strip('-')

Conclusion

Python offre plusieurs méthodes pour créer des slugs. Choisissez celle adaptée à votre projet.