Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

Python - Get original function arguments in decorator

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?

question from:https://stackoverflow.com/questions/1010080/python-get-original-function-arguments-in-decorator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...