假设我在Tornado中有一个JSON-RPC处理程序。在该处理程序中是一个名为start_connection的函数,其中进行了websocket连接。如何在连接成功时返回消息,并在连接失败时返回另一条消息。
我试过了:
class MainHandler(JSONRPCHandler):
def start_connection(self, uuid, addr):
try:
def store_connection(future):
conn = future.result()
# store conn
return {'success': True}
websocket.websocket_connect(addr, io_loop=main_loop, callback=store_connection)
except Exception, e:
return {'success': False, 'error_message': str(e)}
但这不起作用,因为成功消息不是从start_connection
返回的,而是从回调中返回的。我还尝试使用gen.coroutine
装饰器并在yield
之前添加websocket_connect
关键字,但这导致了错误:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1115, in _stack_context_handle_exception
raise_exc_info((type, value, traceback))
File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1298, in wrapper
result = method(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/tornadorpc/tornadorpc/base.py", line 259, in post
self._RPC_.run(self, request_body)
File "/usr/lib/python2.7/dist-packages/tornadorpc/tornadorpc/base.py", line 103, in run
self.dispatch(request[0], request[1])
File "/usr/lib/python2.7/dist-packages/tornadorpc/tornadorpc/base.py", line 145, in dispatch
final_kwargs, extra_args = getcallargs(method, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/tornadorpc/tornadorpc/utils.py", line 23, in getcallargs
self_key = args.pop(0)
IndexError: pop from empty list
有人知道如何解决这个问题吗?
答案 0 :(得分:0)
我是龙卷风的新手,但让我试试。
在异步服务器中回调的整个想法是不是它会被称为LATER,这是websocket_connect()
退出后的明显时间?
我相信你必须在回调本身处理结果,或者做类似
的事情future = websocket.websocket_connect( \
addr, io_loop=main_loop, callback=store_connection)
和
future.add_done_callback(some_completion_callback)
或者更确切地说,通过add_done_callback() doc向Tornado推荐,使用IOLoop.add_future():
main_loop.add_future(future, some_completion_callback)
答案 1 :(得分:0)
我的不好,我不得不使用tornadorpc的异步装饰器,如下所述:https://github.com/joshmarshall/tornadorpc#asynchronous-example