218 # convert with type |
214 # convert with type |
219 try : |
215 try : |
220 value = self.type(value) |
216 value = self.type(value) |
221 |
217 |
222 except Exception, e : |
218 except Exception, e : |
223 raise URLError("Bad value %r for type %s: %s" % (value, self.type.__name__, e)) |
219 raise URLError("Bad value %r for type %s: %s: %s" % (value, self.type.__name__, type(e).__name__, e)) |
224 |
220 |
225 return LabelValue(self, value) |
221 return LabelValue(self, value) |
226 |
222 |
227 def __str__ (self) : |
223 def __str__ (self) : |
228 return '{%s%s%s}' % ( |
224 return '{%s%s%s}' % ( |
229 self.key, |
225 self.key, |
230 ':%s' % (self.type.__name__ ) if self.type != str else '', |
226 ':%s' % (self.type.__name__ ) if self.type != str else '', |
231 '=%s' % (self.default, ) if self.default else '', |
227 '=%s' % (self.default, ) if self.default else '', |
232 ) |
228 ) |
233 |
229 |
|
230 class URLConfig (object) : |
|
231 """ |
|
232 Global configuration relevant to all URLs |
|
233 """ |
|
234 |
|
235 # built-in type codes |
|
236 BUILTIN_TYPES = { |
|
237 # default |
|
238 None : str, |
|
239 |
|
240 # integer |
|
241 'int' : int, |
|
242 } |
|
243 |
|
244 def __init__ (self, type_dict=None) : |
|
245 """ |
|
246 Create an URLConfig for use with URL |
|
247 |
|
248 If type_dict is given, it should be a mapping of type names -> callables, and they will be available for |
|
249 type specifications in addition to the defaults. |
|
250 """ |
|
251 |
|
252 # build our type_dict |
|
253 self.type_dict = self.BUILTIN_TYPES.copy() |
|
254 |
|
255 # apply the given type_dict |
|
256 if type_dict : |
|
257 self.type_dict.update(type_dict) |
|
258 |
234 class URL (object) : |
259 class URL (object) : |
235 """ |
260 """ |
236 Represents a specific URL |
261 Represents a specific URL |
237 """ |
262 """ |
238 |
263 |
239 def __init__ (self, url_mask, handler, **defaults) : |
264 |
240 """ |
265 def __init__ (self, config, url_mask, handler, type_dict=None, **defaults) : |
241 Create an URL with the given url mask, handler, and default values |
266 """ |
|
267 Create an URL using the given URLConfig, with the given url mask, handler, and default values. |
242 """ |
268 """ |
243 |
269 |
244 # store |
270 # store |
|
271 self.config = config |
245 self.url_mask = url_mask |
272 self.url_mask = url_mask |
246 self.handler = handler |
273 self.handler = handler |
247 self.defaults = defaults |
274 self.defaults = defaults |
248 |
275 |
249 # build our labels |
276 # build our labels |
250 self.label_path = [Label.parse(mask, defaults) for mask in url_mask.split('/')] |
277 self.label_path = [Label.parse(mask, defaults, config.type_dict) for mask in url_mask.split('/')] |
251 |
278 |
252 def get_label_path (self) : |
279 def get_label_path (self) : |
253 """ |
280 """ |
254 Returns a list containing the labels in this url |
281 Returns a list containing the labels in this url |
255 """ |
282 """ |