in Flask, PYTHON, Python Packages, Web Development

Slugify

Today while working on the flask casts site, I decided it would be a good idea to generate a url slug. This is extremely important for search engine optimization. I thought about writing my own class to do this, then thought it might get ugly…so I searched for a package. I found Slugify: https://github.com/un33k/python-slugify

Pretty simple to use. When creating the Post object I just modified my __init__ to the following:

    def __init__(self, title, content, author, created=None):
        self.title = title
        self.slug = slugify(title)
        self.content = content
        self.author = author
        self.created = datetime.datetime.utcnow().strftime('%A %x @ %H:%M:%S') \
            if created is None else created

Now I can pass the slug to a url like: flaskcasts.com/post/this-is-the-post-title

@home.route('/post/<string:slug>')
def post(slug):
    post = Post.get_post(slug)
    author = User.get_user(post['author'])
    return render_template('home/post.html', post=post, author=author['fullname'])

Thanks for reading!

Write a Comment

Comment