最近在使用 Tornado,用到 gen.coroutine 和 yield 配合,但是出了些问题,一直不明白!
代码:
class BaseHandler(tornado.web.RequestHandler):
@gen.coroutine
def args_kwargs(self,pro):
try:
kwargs = self.get_argument("data",None)
if kwargs:
code="-10000"
raise gen.Return(code)
except:
print traceback.format_exc()
class EventAPIHandler(BaseHandler):
@gen.coroutine
def post(self):
try:
code = yield self.args_kwargs("event")
if code:
self.write(re_code[code])
self.finish()
except Exception,e:
print traceback.format_exc()
错误为:
Traceback (most recent call last):
File "server.py", line 124, in args_kwargs
raise gen.Return(code)
Return
不能返回数据,请问有大神知道原因吗?请指教,非常感谢!
阿神2017-04-17 17:32:03
Python2.x では、ジェネレーターは直接 return 值
できないため、Tornado は値を特別な例外にラップして返します。この例外は gen.Return
であるため、try..Except はこの例外をキャッチし、エラーが発生します。報告されているので、BaseHandler.args_kwargs
のコードを変更します。
には、yield はないようです。args_kwargs
を使用する必要はありません。 > そうですよね? gen.coroutine
リーリー