slug.py :  » Content-Management-Systems » PyLucid » PyLucid_standalone » pylucid_project » utils » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Content Management Systems » PyLucid 
PyLucid » PyLucid_standalone » pylucid_project » utils » slug.py
# -*- coding: utf-8 -*-

"""
    Slug
    ~~~~
    
    A slug is a short label for something, containing only letters, numbers, underscores or hyphens.
    Theyre generally used in URLs. See also: http://docs.djangoproject.com/en/dev/glossary/

    Some usefull routines around unique slug.

    Last commit info:
    ~~~~~~~~~~~~~~~~~
    $LastChangedDate$
    $Rev$
    $Author$

    :copyleft: 2007-2009 by the PyLucid team, see AUTHORS for more details.
    :license: GNU GPL v3 or above, see LICENSE for more details.
"""

import string

ALLOW_CHARS = string.ascii_letters + string.digits + "_"
SEPERATOR = "-"

def verify_slug(slug):
    """
    Check a slug. Raise AssertionError if something seems to be wrong.
    But normaly the urls-re should only filter the bad thing from urls ;)
    
    >>> verify_slug("ThisIs-A-Slug_123")
    
    >>> verify_slug("")
    Traceback (most recent call last):
    ...
    AssertionError: Slug is empty!
    
    >>> verify_slug("Wrong!")
    Traceback (most recent call last):
    ...
    AssertionError: Not allowed character in slug: '!'
    """
    if slug=="":
        raise AssertionError("Slug is empty!")

    for char in slug:
        if not char in ALLOW_CHARS+SEPERATOR:
            raise AssertionError(
                "Not allowed character in slug: %r" % char
            )


def makeUniqueSlug(item_name, existing_slugs=[]):
    """
    returns a URL safe, unique slug.
    - delete all non-ALLOW_CHARS characters.
    - if the shotcut already exists in existing_slugs -> add a sequential number
    Note:
    Not only used for making page slugs unique with getUniqueSlug(),
    also used in:
        -PyLucid.defaulttags.lucidTag.lucidTagNode._add_unique_div()
        -PyLucid.middlewares.headline_anchor.HeadlineAnchor()
    
    >>> makeUniqueSlug("Please make *me* slug!")
    'Please-make-me-slug'
    >>> makeUniqueSlug("And me - too! -, please.")
    'And-me-too-please'
    
    >>> existing_slugs = ["Exist", "ExistToo", "ExistToo1"]
    >>> makeUniqueSlug("NewItem", existing_slugs)
    'NewItem'
    >>> makeUniqueSlug("Exist", existing_slugs)
    'Exist1'
    >>> makeUniqueSlug("ExistToo", existing_slugs)
    'ExistToo2'
    
    to make a slug unique we ignore case!
    >>> makeUniqueSlug("SLUG", existing_slugs=['slug',"Slug1"])
    'SLUG2'
    
    If item is empty, we get '1' back:
    >>> makeUniqueSlug("", [])
    '1'
    """
    # delete all non-ALLOW_CHARS characters and separate in parts
    parts = [""]
    for char in item_name:
        if not char in ALLOW_CHARS:
            if parts[-1] not in ("", SEPERATOR):
                # No double "-" e.g.: "foo - bar" -> "foo-bar" not "foo---bar"
                parts.append("")
        else:
            parts[-1] += char

    item_name = SEPERATOR.join(parts)
    item_name = item_name.strip(SEPERATOR)

    if item_name == "":
        # No slug? That won't work.
        item_name = "1"
        
    if existing_slugs==[]:
        return item_name

    existing_slugs2 = [i.lower() for i in existing_slugs]

    # make double slug unique (add a new free sequential number)
    if item_name.lower() in existing_slugs2:
        for i in xrange(1, 1000):
            testname = "%s%i" % (item_name, i)
            if testname.lower() not in existing_slugs2:
                item_name = testname
                break

    return item_name


#def getUniqueSlug(slug, exclude_slug=None):
#    from PyLucid.models import Page
#
##    print "source slug:", slug
#    slugs = Page.objects.values("slug")
##    print "exclude slug: '%s'" % exclude_slug
#    if exclude_slug != None:
#        slugs = slugs.exclude(slug=exclude_slug)
#    existing_slugs = [i["slug"] for i in slugs]
##    print "existing_slugs:", existing_slugs
#    return makeUniqueSlug(slug, existing_slugs)



if __name__ == "__main__":
    #
    # There exist a unitest for the page slugs:
    #     ./unittests/unittest_UniqueSlugs
    #
    import doctest
    doctest.testmod(
#        verbose=True
        verbose=False
    )
    print "DocTest end."
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.