Skip to content

Instantly share code, notes, and snippets.

@encukou
Created November 14, 2011 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save encukou/1365007 to your computer and use it in GitHub Desktop.
Save encukou/1365007 to your computer and use it in GitHub Desktop.
Some ideas for a Resource class
from pyramid.decorator import reify
from pyramid.renderers import render
from pyramid.response import Response
class Resource(object):
"""A Pyramid resource
Resources are lightweight objects tied to a request. They provide URL
traversal and view rendering.
"""
def __init__(self, request, parent, name=None):
self.parent = self.__parent__ = parent
self.request = request
if name is not None:
self.name = name
@property
def __name__(self):
return self.name
@property
def title(self):
return self.name
@property
def title_in_page(self):
return self.title
@property
def title_in_head(self):
site_title = self.request.spline.settings['spline.site_title']
if self.title:
return self.title + '-' + site_title
else:
return site_title
def __getitem__(self, name):
"""Get a child resource.
There are two kinds of child resources controllers: ones that have a
static, built-in name (such as "search" or "edit"), and dynamic ones
such as user/joe or tag/cats.
I like to treat these as very separate concepts.
To create the first kind, provide a child_* attribute that returns the
appropriate Resource class.
For resources with dynamic names, override the `get_child` method().
"""
static = getattr(self, 'child_' + name, None)
try:
dynamic = self.get_child(name)
except KeyError:
dynamic = None
if static:
if dynamic:
raise LookupError('%s: Ambiguous name' % name)
return static(self.request, self, name)
elif dynamic:
return dynamic(self.request, self)
else:
raise KeyError(name)
@reify
def url(self):
return self.request.resource_url(self)
def get_child(self, name):
raise KeyError
def __resource_url__(self, request, info):
# We don't want trailing slashes
return request.application_url + info['virtual_path'].rstrip('/')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment