Introduction to Slugify
The slugify library is a powerful tool that simplifies the process of creating URL-friendly strings, or “slugs”, from a variety of raw inputs. It ensures your URLs are clean, readable, and optimized for SEO. In this guide, we’ll explore dozens of useful APIs provided by slugify with illustrative code snippets and a complete application example.
Basic Usage
from slugify import slugify
title = "Hello World! This is a test."
slug = slugify(title)
print(slug) # Output: hello-world-this-is-a-test
Advanced Configurations
Custom Separator
slug = slugify("Hello World!", separator="_")
print(slug) # Output: hello_world
Handling Unicode
slug = slugify("你好,世界")
print(slug) # Output: ni-hao-shi-jie
Removing Stop Words
stop_words = ['a', 'the', 'is']
slug = slugify("This is a test of the slugify library", stopwords=stop_words)
print(slug) # Output: this-test-slugify-library
Slugifying Objects
obj = {"key-one": "Hello", "key-two": "World"}
slug = slugify(obj, separator=":")
print(slug) # Output: hello:world
Decoding URLs
slug = slugify("Dusty Springfield & Massive Attack")
print(slug) # Output: dusty-springfield-massive-attack
Application Example
Let’s build a small web app using Flask that leverages slugify to create SEO-friendly URLs for blog posts:
from flask import Flask, request, jsonify
from slugify import slugify
app = Flask(__name__)
@app.route('/create-post', methods=['POST'])
def create_post():
data = request.get_json()
title = data.get('title')
slug = slugify(title)
return jsonify({"title": title, "slug": slug})
if __name__ == '__main__':
app.run(debug=True)
In this example, we create a simple Flask app that accepts a blog post title and returns its SEO-friendly slug.
Hash: a82dcddba426288f244ff3288721891ceb2aa4b41e247a8779dade450619485a