Alex Rivera | Logout

Accessing function arguments from decorator

Asked 2011-06-24T15:26:21.007
11

I have a Request handler and a decorator, I would like to work with the self object inside the decorator

class MyHandler(webapp.RequestHandler):

    @myDecorator
        def get(self):
            #code

Update: Please notice the difference between the first and second self

class myDecorator(object):

    def __init__(self, f):
        self.f = f

    def __call__(self):
        #work with self
  1. MyHandler > get ( function ) > self ( argument )
  2. myDecorator > __call__ ( function ) > self ( argument )

the self arguments mentioned above are different. My intention is to access the first self from inside __call__ function, or find a way to do something similar.

Hi can I access MyHandlers self argument from get function inside the decorator?

Update2: I want to implement a decorator to work with a custom login in google app engine:

I have a class ( requestHandler ):

class SomeHandler(webapp.RequestHandler):
    @only_registered_users
    def get(self):
        #do stuff here

And I want to decorate the get function in order to check out if the user is logged in or not:

from util.sessions import Session
import logging

class only_registered_users(object):

    def __init__(self, f):
        self.f = f

    def __call__(self):
        def decorated_get(self):
        logging.debug("request object:", self.request)
        session = Session()

        if hasattr(session, 'user_key'):
            return self.f(self)
        else:
            self.request.redirect("/login")


    return decorated_get

I know if a user is logged in if has the property 'user_key' in a session Object.

That's the main goal I'm interested in on this specific case

Edit
Report

1 Answer

1

Try this approach: Can a Python decorator of an instance method access the class?

Not the exact same question but you should be able to use the same approach to create a reference to self or a reference to a dictionary with objects of a certain class in it that you can get out in your decorator.

answered 2011-06-24T15:40:59.483

Your Answer