Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Routes enhancements

View gist:260907
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
"Fixes and enhancements to Routes 1.11 - see http://positiveincline.com/?p=561"
 
# NB: superceded by http://bitbucket.org/asplake/routes/
 
import routes.mapper
 
COLLECTION_ACTIONS = ['index', 'create', 'new']
MEMBER_ACTIONS = ['show', 'update', 'delete', 'edit']
 
class SubMapperParent(object):
def submapper(self, **kwargs):
return SubMapper(self, **kwargs)
 
def collection(
self,
collection_name,
resource_name,
path_prefix=None,
member_prefix='/{id}',
controller=None,
collection_actions=COLLECTION_ACTIONS,
member_actions = MEMBER_ACTIONS,
member_options=None,
**kwargs):
if not controller:
controller =resource_name or collection_name
if not path_prefix:
path_prefix = '/' + collection_name
collection = SubMapper(
self,
collection_name=collection_name,
resource_name=resource_name,
path_prefix = path_prefix,
controller=controller,
actions=collection_actions,
**kwargs)
collection.member = SubMapper(
collection,
path_prefix = member_prefix,
actions=member_actions,
**(member_options or {}))
 
return collection
 
# Define a new Mapper that knows about our enhanced SubMapper
class Mapper(SubMapperParent, routes.Mapper):
# Pretty string representation
def __str__(self):
def format_methods(r):
if r.conditions:
method = r.conditions.get('method', '')
return method if type(method) is str else ', '.join(method)
else:
return ''
 
table = [('Route name', 'Methods', 'Path')] + [
(
r.name or '',
format_methods(r),
r.routepath or ''
)
for r in self.matchlist]
widths = [
max(len(row[col]) for row in table)
for col in range(len(table[0]))]
return '\n'.join(
' '.join(row[col].ljust(widths[col]) for col in range(len(widths)))
for row in table)
 
# Add some new tricks to SubMapper
class SubMapper(SubMapperParent, routes.mapper.SubMapper):
# Save a resource name on initialisation, defaulting it to the controller name
def __init__(self, obj, resource_name=None, collection_name=None, actions=None, **kwargs):
routes.mapper.SubMapper.__init__(self, obj, **kwargs)
self.collection_name = collection_name
self.member = None
self.resource_name = resource_name \
or getattr(obj, 'resource_name', None) \
or kwargs.get('controller', None) \
or getattr(obj, controller, None)
 
self.add_actions(actions or [])
 
# Fix known bug, support merging of dict-valued options (needed for nested collections)
def connect(self, *args, **kwargs):
newkargs = {}
newargs = args
for key, value in self.kwargs.items():
if key == 'path_prefix':
if len(args) > 1: # was len(args > 1)
newargs = (args[0], value + args[1])
else:
newargs = (value + args[0],)
elif key in kwargs:
if isinstance(value, dict):
newkargs[key] = dict(value, **kwargs[key]) # merge dicts
else:
newkargs[key] = value + kwargs[key]
else:
newkargs[key] = self.kwargs[key]
for key in kwargs:
if key not in self.kwargs:
newkargs[key] = kwargs[key]
return self.obj.connect(*newargs, **newkargs)
# Generate a subresource linked by "rel", e.g.
#
# with mapper.submapper(controller='thing', path_prefix='/things') as c:
# c.link('new')
# with c.submapper(path_prefix='/{id}')) as m:
# m.link('edit')
#
# generates
#
# mapper.connect(
# 'new_thing', '/things/edit',
# controller='thing', action='new',
# conditions={'method': 'GET'})
# mapper.connect(
# 'edit_thing', '/things/{id}/edit',
# controller='thing', action='edit',
# conditions={'method': 'GET'})
#
# Overridable defaults:
# name: {rel}_{self.resource_name}
# action: rel
# rel: name
# method: 'GET'
#
# At least one of rel and name (the route name) must be supplied. It would
# be unusual not to supply rel.
#
def link(self, rel=None, name=None, action=None, method='GET', **kwargs):
return self.connect(
name or (rel + '_' + self.resource_name),
'/' + (rel or name),
action=action or rel or name,
**_kwargs_with_conditions(kwargs, method))
 
def new(self, **kwargs):
return self.link(rel='new', **kwargs)
 
def edit(self, **kwargs):
return self.link(rel='edit', **kwargs)
 
# Generate an action (typically with the POST method) on a resource that
# supports other methods (typically GET).
#
# with mapper.submapper(controller='thing', path_prefix='/things') as m:
# with m.submapper(path_prefix='/{id}')) as o:
# o.action('show', name='thing')
# o.action('update', method='PUT')
#
# generates
#
# mapper.connect(
# 'thing', '/things/{id}',
# controller='thing', action='show',
# conditions={'method': 'GET'})
# mapper.connect(
# 'save_thing', '/things/{id}',
# controller='thing', action='update',
# conditions={'method': 'PUT'})
#
# Overridable defaults:
# name: {action}_{self.resource_name}
# action: name
# method: GET
#
# At least one of name (the route name) and action must be supplied.
#
def action(self, name=None, action=None, method='GET', **kwargs):
return self.connect(
name or (action + '_' + self.resource_name),
'',
action=action or name,
**_kwargs_with_conditions(kwargs, method))
def index(self, name=None, **kwargs):
return self.action(
name=name or self.collection_name,
action='index', method='GET', **kwargs)
 
def show(self, name = None, **kwargs):
return self.action(
name=name or self.resource_name,
action='show', method='GET', **kwargs)
 
def create(self, **kwargs):
return self.action(action='create', method='POST', **kwargs)
def update(self, **kwargs):
return self.action(action='update', method='PUT', **kwargs)
 
def delete(self, **kwargs):
return self.action(action='delete', method='DELETE', **kwargs)
 
def add_actions(self, actions):
[getattr(self, action)() for action in actions]
 
 
# Create kwargs with a 'conditions' member generated for the given method
def _kwargs_with_conditions(kwargs, method):
if method and 'conditions' not in kwargs:
newkwargs = kwargs.copy()
newkwargs['conditions'] = {'method': method}
return newkwargs
else:
return kwargs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.