Search code examples
pythonhandlertornadoself

self.finish() error in Tornado


I have a problem.

I have this part of code:

        if command in ['ON', 'OFF', 'TOGGLE']:
        ret['success'] = "The %s command has been succesfully sent!" % (command.upper())
        self.write(tornado.escape.json_encode(ret))
        self.finish()
    elif command == 'HOWMANY':
        opcodegroupr = "A0"
        opcoder = "85"
    elif command == 'IDENTIFY':
        opcodegroupr = "A0"
        opcoder = "81"

I want finish the handler for command on, off, toggle. Instead, for commands howmany and identify i would create new variables for other elaborations.

But when I send for example the on command I obtain this error:

File "./wsn.py", line 1024, in get
'&opcode_group=', opcodegroupr,
UnboundLocalError: local variable 'opcodegroupr' referenced before assignment

like the self.finish() doesn't close the handler.

Where is the problem?

Thank you very much.


Solution

  • With only this partial code I'm assuming you're missing the return. self.finish() closes the request, but doesn't return from the function.

    if command in ['ON', 'OFF', 'TOGGLE']:
        ret['success'] = "The %s command has been succesfully sent!" % (command.upper())
        self.write(tornado.escape.json_encode(ret))
        self.finish()
        return           # self.finish() finishes the request - doesn't return
    else ...