Вопрос

So I'm trying to make a decorator for my django view and I have it sort of working. The decorator looks like

# Decorator for the function - update(request, extra=None)
def check_super(view):
    def wrapper(request, *args, **kwargs):
        status = supercheck(request)

        if status=="USER":
            raise PermissionDenied
        else:
            args = [a for a in args]
            kwargs = dict((k, v) for k, v in kwargs.items())
            kwargs.update({'status':status})    # Offending line
            return view(request, *args, **kwargs)

    return wrapper

Basically I do a check with the supercheck function and I want to pass the result of that as another argument to my function but the line stated above results in the error

update() got an unexpected keyword argument 'status'

kwargs is just a dictionary, right? So I should be able to add new bindings to it like that but it keeps giving me that error. Doing it this way also results in the same errror

kwargs['status']=status
Это было полезно?

Решение 2

Bah, I figured it out. Turns out all I had to do was make sure the original function took *args and **kwargs, which is much easier to generalize (since I don't know how these functions will be)

So my function update() now has the signature

update(request, extra=None, *args, **kwargs)

And I can pass in "arbitrary" keywords by updating kwargs before I wrap it. Thanks for the clarification. The comments helped me narrow down what the issue was!

The only caveat is that I access status in the update function with

kwargs['status'] 

instead of just

status

Which isn't too bad

Другие советы

I don't know why you're getting that -- I can't reproduce it on my machine.

That said, the easiest way to do what you want is to forget the mucking about with args and kwargs and just do

else:
    return view(request, *args, status=status, **kwargs)

assuming you know view takes an argument called 'status'. (If it doesn't, as John Spong said, well, there's your problem.)

Here's a bit more on *args, **kwargs, and ** in functions.

That said, it looks like all you want to do is check that the user passes your supercheck function. Check out the @user_passes_test decorator - it does exactly what you want.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top