Skip to content

Instantly share code, notes, and snippets.

@reedobrien
Created February 1, 2011 20:13
Show Gist options
  • Save reedobrien/806569 to your computer and use it in GitHub Desktop.
Save reedobrien/806569 to your computer and use it in GitHub Desktop.
Tres Traversal placeholder example
"""
On 01/30/2011 09:04 AM, Wade Leftwich wrote:
If you want to stick with Traversal, don't forget that you have
request.subpath available to you. For the path "/blog/archive/
2011/01/29/my-post-about-pyramid", you could have an Archive context
whose default (unnamed) view would be called with a request that
included request.subpath = ['2011', '01', '29', 'my-post-about-
pyramid'].
Other traversal-based strategies:
- - an 'archive' view registered for the blog context (assuming you don't
otherwise need the 'archive' context).
- - add non-persistent placeholder objects to your app to take advantage
of traversal's use of '__getitem__'. This solution allows you write
views for the "transient" context classes, even though they aren't in
your database. E.g., something like:
"""
class Blog:
...
def __getitem__(self, key):
if key == 'archive':
return Archive(self)
return super(Blog, self).__getitem__(key)
class Archive:
__name__ = 'archive'
YEARS = range(2010, 2100)
def __init__(self, blog):
self.__parent__ = self.blog = blog
def __getitem__(self, key):
try:
year = int(key)
except TypeError:
raise KeyError(key)
if year not in self.YEARS:
raise KyeError(key)
return ArchiveYear(self, year)
class ArchiveYear:
__name__ = 'archive'
MONTHS = range(1, 12)
def __init__(self, archive, year):
self.__parent__ = archive
self.__name__ = str(year)
self.blog = archive.blog
self.year = year
def __getitem__(self, key):
try:
mnnth = int(key)
except TypeError:
raise KeyError(key)
# or, return self.blog.entries[key]
if month not in self.MONTHS:
raise KeyError(key)
return ArchiveMonth(self, month)
class ArchiveMonth:
__name__ = 'archive'
MONTHS = range(1, 12)
def __init__(self, year, month):
self.__parent__ = year
self.__name__ = str(month)
self.blog = year.blog
self.month = month
def __getitem__(self, key):
return self.blog.entries[key]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment