0

I am getting NameError: name 'setup_iprotect_session' is not defined when tring to call a decorator even though it's present in the same class.

I tried to remove the self argument but it didn't help much.

Am I doing something wrong here?

Decorator

class Synchronize(Resource):
    def get(self):
        self.get_lastcardusage()

    @setup_iprotect_session()
    def get_lastcardusage(self):
        self.iprotect_client.post('SELECT RCN FROM ACCESSKEY')

    def setup_iprotect_session(self):
        def decorator(func):
            @wraps(func)
            def wrapper(*args, **kwargs):
                self.iprotect_client = IProtect()
                self.iprotect_client.authenticate()
                func(*args, **kwargs)
                self.iprotect_client.logout()
            return wrapper
        return decorator

Full traceback

Traceback (most recent call last):
  File "wsgi.py", line 1, in <module>
    from app import app
  File "/Users/om/app/__init__.py", line 27, in <module>
    from .iprotect_api.views import iprotect_api
  File "/Users/om/iprotect_api/views.py", line 15, in <module>
    from .synchronize import Synchronize, LastSync, Keepalive
  File "/Users/om/iprotect_api/synchronize.py", line 13, in <module>
    class Synchronize(Resource):
  File "/Users/om/iprotect_api/synchronize.py", line 71, in Synchronize
    @setup_iprotect_session()
NameError: name 'setup_iprotect_session' is not defined
Omar Abdelrazik
  • 683
  • 2
  • 9
  • 30
  • Does [this](https://stackoverflow.com/questions/1263451/python-decorators-in-classes) help? – Almog-at-Nailo Jul 26 '21 at 07:58
  • 2 problems. Remove parentheses from @setup_iprotect_session() then move the declaration of setup_iprotect_session above get_lastcardusage. That will correct your stated runtime error. Whether this is the right/best way to declare your decorator is another matter altogether –  Jul 26 '21 at 08:00

1 Answers1

0

As suggested by this answer, you can try setting setup_iprotect_session as a staticmethod of the class, and then you won't have issues with self not being defined

class Synchronize(Resource):
    def get(self):
        self.get_lastcardusage()

    def setup_iprotect_session(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            self.iprotect_client = IProtect()
            self.iprotect_client.authenticate()
            func(*args, **kwargs)
            self.iprotect_client.logout()

        return wrapper

    @setup_iprotect_session
    def get_lastcardusage(self, a, b=None):
        self.iprotect_client.post('SELECT RCN FROM ACCESSKEY')

    setup_iprotect_session = staticmethod(setup_iprotect_session)
Almog-at-Nailo
  • 1,152
  • 1
  • 4
  • 20