gearman function in worker remains undefined

71 views Asked by At

I have pretty simple code of worker, might be doing some silly mistake.

class BingWorker(object):
    def __init__(self):
        self.gm_worker = gearman.GearmanWorker(['localhost:4730'])
        completed_job_request = self.gm_worker.register_task('bingmedia', callBing)

    def callBing(self, gearman_worker, gearman_job):
        print "In worker ", gearman_job.data
        return "Kools"

    def run(self):
        self.gm_worker.work()

if __name__ == '__main__':
    BingWorker().run()

gives

Traceback (most recent call last):
  File "worker.py", line 16, in <module>
    BingWorker().run()
  File "worker.py", line 6, in __init__
    completed_job_request = self.gm_worker.register_task('bingmedia', callBing)
NameError: global name 'callBing' is not defined

any hints? example is very similar to python example at http://gearman.org/examples/reverse/. just put in class structure

Improved code:

class BingWorker(object):
    def __init__(self):
        self.gm_worker = gearman.GearmanWorker(['localhost:4730'])

    def callBing(self, gearman_worker, gearman_job):
        print "In worker ", gearman_job.data
        return "Kools"

    def run(self):
        completed_job_request = self.gm_worker.register_task('bingmedia', self.callBing)
        self.gm_worker.work()

if __name__ == '__main__':
    BingWorker().run()
1

There are 1 answers

2
Steve Barnes On BEST ANSWER

You need to change callBing to self.callBing and it might be better to move the registration to the first line of the run method rather than the __init__ method.

The fist is because callBing is a reference to a missing global while self.callBing is a reference to the classes method. The second is because potentially you could get a call to self.callBing before init has finished which would be bad news.