Python For Programmers

by Amit Upadhyay

Useful Libraries

Django Related Libraries

smarturls

smarturls comes with a library of regularly used regular expression patterns to easy regex creation for django urls. The library can be extended by using django setting system.

Install smarturls

$ pip install smarturls

smarturls==0.1.6 | PyPI | GitHub

Example usage

This is how normal django urls.py looks like:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    ('^book/(?P<bookid>\d+)/$', 'some.view'),
    (
        '^author/(?P<author_name>[-\w]+)/$', 
        'some.other.view'
    ),
    ('^year/(?P<year>\d{4,4})/$', 'year.view'),
    (
        '^year/(?P<year>\d{4,4})/(?P<month>\w+)/$', 
        'month.view'
    ),
)

This is how it looks like with smarturls:

from django.conf.urls.defaults import *
from smarturls import surl

urlpatterns = patterns('',
    surl('/book/<int:bookid>/', 'some.view'),
    surl(
        '/author/<slug:author_name>/', 
        'some.other.view'
    ),
    surl('/year/<int4:year>/', 'year.view'),
    surl(
        '/year/<int4:year>/<word:month>/', 
        'month.view'
    ),
)

Custom patterns

Existing patterns can be overwritten and new ones can be defined by defingin the django setting SURL_REGEXERS.

Eg, in settings.py:

SURL_REGEXERS = {
    # overwrite slug: always start with alphanumeric
    "slug": "\w[-\w]*", 

     # now you can use /author/<username:author>/ etc
    "username": "\w+"  
}

Default Patterns

By default smarturls comes with the following patterns:


-- AmitU

PS: You have been reading a section from a book on python that I am writing. I will be releasing a section every week or so on amitu.com/python/. Please subscribe to my mailing list if you want to be notified when a new section is published.