Commits

jmo...@robin  committed d8ea4e6

roud off docs, push a bunch of docs into dselector itself

  • Participants
  • Parent commits a0cc0df

Comments (0)

Files changed (5)

- Copyright (c) 2010, Jason Moiron & Jeremy Self
+ Copyright (c) 2010, Jason Moiron
 
  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
+django-selector
+---------------
+
+Django-Selector is a custom url pattern parser for Django that is based off of
+`Luke Arno's Selector<http://lukearno.com/projects/selector/>`_ for WSGI.  It
+is designed to simplify the writing and reading of url patterns by providing
+recipes for frequently used patterns.  Django-Selector's parser ignores classic
+regex based url patterns, so if you require the flexibility of regexes you
+needn't jump through registration hoops for a one-off url pattern. Using these
+named patterns in your urls.py clarifies *what* they are matching as well as
+*how* they are matching it::
+
+    patterns('foo.views',
+        (r'^/(?P<name>[a-zA-Z0-9\-]+)/(?P<foos>\d*.?\d+)/$', 'index', {}, 'foo-index')
+
+becomes::
+
+    parser.patterns('foo.views',
+        (r'/{name:slug}/{foos:number}/', 'index', {}, 'foo-index'))
+
+You can install django-selector with pip:
+
+    pip install johnny-cache
+
+You can fork django-selector `from its hg repository
+<http://dev.jmoiron.net/hg/django-selector>`_:
+
+    hg clone http://dev.jmoiron.net/hg/django-selector
+
+You can also read the full `current development documentation
+<http://dev.jmoiron.net/django-selector/>`_ or the `release documentation
+<http://packages.python.org/django-selector/>`_.
+

File docs/conf.py

 
 # Add any Sphinx extension module names here, as strings. They can be extensions
 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = []
+extensions = ['sphinx.ext.autodoc']
 
 # Add any paths that contain templates here, relative to this directory.
 templates_path = ['_templates']

File docs/index.rst

    You can adapt this file completely to your liking, but it should at least
    contain the root `toctree` directive.
 
-Welcome to django-selector's documentation!
-===========================================
+django-selector
+---------------
 
-Contents:
+.. automodule:: dselector
 
-.. toctree::
-   :maxdepth: 2
+.. highlight:: sh
 
-Indices and tables
-==================
+You can install django-selector with pip::
 
-* :ref:`genindex`
-* :ref:`modindex`
-* :ref:`search`
+    pip install johnny-cache
 
+You can fork django-selector `from its hg repository
+<http://dev.jmoiron.net/hg/django-selector>`_::
+
+    hg clone http://dev.jmoiron.net/hg/django-selector
+
+.. highlight:: python
+
+Usage
+-----
+
+Here's an example of how a ``urls.py`` file might look when using 
+django-selector::
+
+    from django.contrib import admin
+    from django.conf import settings
+    import dselector
+
+    admin.autodiscover()
+
+    parser = dselector.Parser()
+    urlpatterns = parser.patterns('',
+        (r'admin/(.*)!', admin.site.root),
+    )
+    urlpatterns += parser.patterns('myblog',
+        (r'blog/{page:digits}/', 'list', {}, 'blog-list'),
+        (r'blog/{slug:slug}/', 'detail', {}, 'blog-detail'),
+        (r'archive/{year:year}/', 'archive', {}, 'blog-year'),
+        (r'archive/{year:year}/{month:month}/', 'archive', {}, 'blog-month'),
+        (r'archive/{year:year}/{month:month}/{day:day}/', 'archive', {}, 'blog-day'),
+        (r'comment/post/{content_type:slug}/{id:digits}/', 'comment_post', {}, 'comment-post'),
+    )
+
+    if settings.DEBUG:
+        urlpatterns += parser.patterns('django.views.static',
+            r('media/{path:any}', 'serve', {'document_root' : './media/'}),
+        )
+
+The primary way of denoting url parts with django-selector's parser is via the
+named patterns syntax:  ``{name:pattern}``.  This is parsed into a regular
+expression looking roughly like::
+
+    '(?P<name>%s)' % (pattern_definition)
+
+Refer to the :ref:`pattern-list` for a description of all default patterns.
+
+In addition to translating the shorthand named-pattern syntax to regex,
+django-selector bookends your string with ``^`` and ``$``, as these are so
+often required that it is cleaner to assume they are implied.  When including
+another modules patterns (as in the ``admin`` example above), you may cancel
+the automatic ``$`` by adding a bang (``!``).  If for whatever reason you
+need a literal bang at the end of your url pattern, you may use ``!!``.
+
+Beyond these preprocessing steps, django-selector's ``parser.patterns``
+operates as the standard ``django.conf.urls.defaults.patterns``.
+
+.. autoclass:: dselector.Parser
+.. automethod:: dselector.Parser.patterns
+
+Defining your own named patterns
+--------------------------------
+
+You can define your own named patterns for use in your parser in two ways:
+
+* you can initialize a parser with kwargs ``Parser(name=pattern, ...)``
+* you can add patterns to a parser with ``Parser.register(name, pattern)``
+
+.. automethod:: dselector.Parser.register
+
+
+.. _pattern-list:
+
+List of builtin named patterns
+------------------------------
+
+=========== ==============================  ===========================================
+ name        regex                           description 
+=========== ==============================  ===========================================
+ word       ``r'\w+'``                       a single word
+ alpha      ``r'[a-zA-Z]+'``                 alphabetic characters 
+ digits     ``r'\d+'``                       digits
+ number     ``r'\d*.?\d+'``                  float or integer numbers
+ chunk      ``r'[^/^.]+'``                   a 'chunk' of text (no / or .)
+ segment    ``r'[^/]+'``                     a url segment (between /'s)
+ any        ``r'.*'``                        anything;  good for paths
+ year       ``r'\d{4}'``                     a 4 digit number
+ month      ``r'(%s)' % '|'.join(months)``   textual abbreviated months (Jan, Feb, etc)
+ day        ``r'\d{1,2}'``                   a one or two digit number
+ slug       ``r'[a-zA-Z0-9\-]+'``            suitable for a "slug field"
+=========== ==============================  ===========================================
+
+**Note** that the default ``month`` pattern uses the locale-aware ``calendar``
+module.  If you want to force a certain locale's months, you should either
+set that locale or re-assign ``month`` in your parser via ``Parser.register``.
+

File dselector.py

 #!/usr/bin/env python
+# -*- coding: utf-8 -*-
 
-"""A Django "port" of Luke Arno's "Selector".
-
-To use, create an instance of Parser in your urls.py.  Parser has special
-implementations of the 'patterns' and 'url' functions that essentially
-parse pattern urls into regular expressions, and pass them to the builtin
-django functions.  Using pattern urls, your urls become more about _what_
-they are matching rather than about _how_ they are matching it:
+"""
+Django-Selector is a custom url pattern parser for Django whose API is based on
+`Luke Arno's Selector <http://lukearno.com/projects/selector/>`_ for WSGI.  It
+is designed to simplify the writing and reading of url patterns by providing
+recipes for frequently used patterns.  Django-Selector's parser ignores classic
+regex based url patterns, so if you require the flexibility of regexes you
+needn't jump through registration hoops for a one-off url pattern. Using these
+named patterns in your urls.py clarifies *what* they are matching as well as
+*how* they are matching it::
 
     patterns('foo.views',
-        (r'^/(?P<name>[a-zA-Z0-9\-]+)/(?P<foos>\d*.?\d+)/$', 'index', {}, 'foo-index')
+        (r'^/(?P<name>[a-zA-Z0-9\-]+)/(?P<foos>\d*.?\d+)/$', 'index', {}, 'foo-index'))
 
-becomes, via patterns:
+becomes::
 
-    parser.patterns('foo.views', (r'/{name:slug}/{foos:num}/', 'index', {}, 'foo-index'))
-
-In addition to the builtin patterns (check `pattern_types`), you may also
-register additional patterns to an instantiated parser in your URLs module,
-or subclass Parser and add them to use throughout your application.
-
-You can optionally end a smart pattern with '!' if you do not want to have
-the trailing $ appended (for use in application entry points).  To end with
-a literal '!', use '!!'.
-
-DSelector is distributed under the MIT license.
+    parser.patterns('foo.views',
+        (r'/{name:slug}/{foos:number}/', 'index', {}, 'foo-index'))
 """
 
 import re
 re_findstr  = r'{%(name)s:%(pattern)s}'
 
 class Parser:
+    """A parser that can process url patterns with named patterns in them."""
     def __init__(self, **extra_patterns):
         self.pattern_types = pattern_types.copy()
         for key, val in extra_patterns.iteritems():
         return pat
 
     def patterns(self, prefix, *args):
-        """A replacement 'patterns' that implements smart url groups."""
+        """A replacement 'patterns' that understands named patterns."""
         pattern_list = []
         for t in args:
             if isinstance(t, (list, tuple)):
         return pattern_list
 
     def url(self, regex, view, kwargs=None, name=None, prefix=''):
-        """A replacement for 'url' that understands smart url groups."""
+        """A replacement for 'url' that understands named patterns."""
         regex = self.parse_pattern(regex)
         return django_url(regex, view, kwargs, name, prefix)