Back to index

plone3  3.1.7
utils.py
Go to the documentation of this file.
00001 from AccessControl.requestmethod import _buildFacade
00002 import inspect
00003 
00004 _default = []
00005 
00006 # This is based on AccessControl.requestmethod.postonly
00007 # It should probably be updated to use the decorator module.
00008 class protect(object):
00009     def __init__(self, *checkers):
00010         self.checkers = checkers
00011 
00012     def __call__(self, callable):
00013         spec = inspect.getargspec(callable)
00014         args, defaults = spec[0], spec[3]
00015         try:
00016             r_index = args.index("REQUEST")
00017         except ValueError:
00018             raise ValueError("No REQUEST parameter in callable signature")
00019 
00020         arglen = len(args)
00021         if defaults is not None:
00022             defaults = zip(args[arglen - len(defaults):], defaults)
00023             arglen -= len(defaults)
00024 
00025         def _curried(*args, **kw):
00026             request = None
00027 
00028             if len(args) > r_index:
00029                 request = args[r_index]
00030 
00031             for checker in self.checkers:
00032                 checker(request)
00033 
00034             # Reconstruct keyword arguments
00035             if defaults is not None:
00036                 args, kwparams = args[:arglen], args[arglen:]
00037                 for positional, (key, default) in zip(kwparams, defaults):
00038                     if positional is _default:
00039                         kw[key] = default
00040                     else:
00041                         kw[key] = positional
00042 
00043             return callable(*args, **kw)
00044 
00045         # Build a facade, with a reference to our locally-scoped _curried
00046         facade_globs = dict(_curried=_curried, _default=_default)
00047         try:
00048             name = callable.__name__
00049             exec _buildFacade(name, spec, callable.__doc__) in facade_globs
00050         except TypeError: # BBB: Zope 2.10
00051             name = '_facade'
00052             exec _buildFacade(spec, callable.__doc__) in facade_globs
00053         return facade_globs[name]
00054