Python – Get original function arguments in decorator

Question:

I am trying to write a “login_required” decorator for the views in a WSGI+Werkzeug application.

In order to do this, I need to get at the user’s session, which is accessible via the Request object that is passed into the view methods.

I can’t figure out how to get at that instance of Request in the decorator, though. I looked at PEP318, specifically the fourth example, but I’m not quite getting it.

Here’s what I’m trying:

def login_required(*args, **kw):
    def goto_login(**kw):
        return redirect(url_for('login'))

    def decorate(f):
        # args[0] should be request
        args[0].client_session['test'] = True
        logged_in = 0
        if logged_in:
            return f
        else:
            return goto_login
    return decorate


@login_required()
@expose('/hello/<string:name>')
def hello(request, name):
    return render_template('say_hello.html', name=name)

but I get an index out of bounds error trying to call args[0].

Is there any way I can get access to the request argument passed into the “hello” function in the “login_required” decorator?

Asked By: ashgromnies

||

Answers:

The decorator login_required is passed the function (hello in this case).

So what you want to do is:

def login_required(f):
    # This function is what we "replace" hello with
    def wrapper(*args, **kw):
        args[0].client_session['test'] = True
        logged_in = 0
        if logged_in:
            return f(*args, **kw)  # Call hello
        else:
            return redirect(url_for('login'))
    return wrapper
Answered By: brian-brazil

kwargs is a dictionary containing argument as keys and values as values.

So all you need to do is check:
some_var = kw['my_property']

Answered By: mafonya
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.