Skip to content

Instantly share code, notes, and snippets.

@jonathancg90
Last active July 11, 2016 03:34
Show Gist options
  • Save jonathancg90/4ac4210ac84973174995377adeb8a075 to your computer and use it in GitHub Desktop.
Save jonathancg90/4ac4210ac84973174995377adeb8a075 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from sqlalchemy.orm import validates
from ..helpers.slugify import slugify
from .main import db
class SluggableMixin(object):
name = db.Column(db.Unicode, nullable=False)
slug = db.Column(db.String, nullable=False, index=True)
@property
def _sluggable_query(self):
"""This query will be used as the base to search for duplicate slugs.
Overwrite it in your models to search in a subset."""
return db.query(self.__class__)
@validates('name')
def _set_slug(self, key, value):
"""Update the slug when the name is set.
DO NOT update the slug when the name change.
"""
if self.slug:
return value
cls = self.__class__
oslug = slugify(value or u'nn').lower()
slug = oslug
num = 1
with db.session.no_autoflush:
query = self._sluggable_query.filter(cls.id != self.id)
while query.filter(cls.slug == slug).count():
slug = '{0}-{1}'.format(oslug, num)
num = num + 1
self.slug = slug or u'nn'
return value
@validates('slug')
def _force_set_slug(self, key, value):
"""Force the slug to have a value"""
if not value:
value = self._set_slug('name', self.name)
return value
@classmethod
def by_slug(cls, slug, **kwargs):
slug = slug.lower()
return db.query(cls).filter(cls.slug == slug).first()
@classmethod
def by_name(cls, name, **kwargs):
slug = slugify(name)
if not slug:
return None
return cls.by_slug(slug, **kwargs)
Funcion:
def slugify(s, space='-', lower=True):
"""
"""
s = normalize(s)
if lower:
s = s.lower()
# remove dots to prevent U.S.A -> U-S-A
s = s.decode("utf-8")
s = s.replace('.', '')
# replace unwanted characters
s = re.sub(r'[^-a-zA-Z0-9]+', space, s)
# remove redundant "-"
if space:
s = re.sub(space + '{2,}', space, s).strip(space)
return s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment