On 2 nov, 19:39, nostradamnit <sam.cranf...@gmail.com> wrote:
> I'm trying to write a custom view decorator that takes a parameter,
> and I can't for the life of me figure out how to pass the parameter.
> I've tried the nested function pattern, the class with __init__ and
> __call__ methods pattern, and I always run into the same basic error.
> It either says I have to many parameters (professional_only expects 1
> param but got 2) or too few parameters (expects only 1 but got 2)

The RightThing(tm) to do when having this kind of problems is to try
to come up with the *minimal* working code reproducing the problem.
Did you try to write a dummy parameterized decorator ? I mean, one
*not* depending on both Django and your application ?



> or
> in it's current state, says that NoneType or the view function is not
> callable?!?

In the "current state", you forgot to return _dec from _check_status.

> Here's a dpaste dump -http://dpaste.org/azgn/

The class version's __call__ method should return the decorated
function. And in the double-nested-function version, you have a path
that (implicitely) returns None (no 'else' branch after line #38). You
may also have problems with your catch-all try/except clause.

Here are working examples of both patterns:

def parameterized_decorator(param):
    def _real_decorator(func):
        def _decorated(*args, **kw):
            _args = ", ".join(map(str, args))
            _kw = ", ".join("%s=%s" % item for item in kw.items())
            print "func %s called with (%s, %s) - param was : %s" %
(func, _args, _kw, param)
            return func(*args, **kw)
        return _decorated
    return _real_decorator

@parameterized_decorator("foo")
def test1(*args, **kw):
    print "in test1() : arg = %s - kw = %s" % (str(args), str(kw))
    return "test1"

class ParameterizedDecorator(object):
    def __init__(self, param):
        self._param = param
        self._func = None

    def __call__(self, func):
        self._func = func
        return self._exec

    def _exec(self, *args, **kw):
        _args = ", ".join(map(str, args))
        _kw = ", ".join("%s=%s" % item for item in kw.items())
        print "func %s called with (%s, %s) - param was : %s" %
(self._func, _args, _kw, self._param)
        return self._func(*args, **kw)


@ParameterizedDecorator("bar")
def test2(*args, **kw):
    print "in test2() : arg = %s - kw = %s" % (str(args), str(kw))
    return "test2"


HTH
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to