Python Slug-Erstellung: Django, Flask und Vanilla Python Anleitung

Lernen Sie alle Methoden zur URL-Slug-Erstellung in Python. Erstellen Sie SEO-freundliche URLs mit Django slugify, python-slugify-Bibliothek und benutzerdefinierten Funktionen.

Was ist ein Slug in Python und warum ist er wichtig?

Ein Slug ist der lesbare und SEO-freundliche Teil einer URL. Das Erstellen von Slugs in Python ist entscheidend für die Suchmaschinenoptimierung Ihrer Webanwendungen.

Methode 1: Vanilla Python Slug-Erstellung

Grundlegende Slug-Funktion ohne Bibliotheken:

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)
    text = text.strip('-')
    text = re.sub(r'-+', '-', text)
    return text

Methode 2: python-slugify Bibliothek

pip install python-slugify

from slugify import slugify
slug = slugify("Hallo Welt!")
print(slug)  # hallo-welt

Methode 3: Django's eingebaute slugify

from django.utils.text import slugify
slug = slugify("Hallo Welt")
print(slug)  # hallo-welt

Deutsche Zeichen korrekt konvertieren

def german_slugify(text):
    de_map = {'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'ß': 'ss'}
    for de_char, en_char in de_map.items():
        text = text.replace(de_char, en_char)
    text = text.lower()
    text = re.sub(r'[^a-z0-9]+', '-', text)
    return text.strip('-')

Fazit

Python bietet mehrere Methoden zur Slug-Erstellung. Wählen Sie die passende für Ihr Projekt.