最近在使用 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
不能返回数据,请问有大神知道原因吗?请指教,非常感谢!
Original, remove the try except, try except will catch the raise, change it to the following, it should be OK
In Python2.x, the generator cannot be directly
return 值
,所以Tornado把值包在一个特殊的异常里返回出来,这个异常就是gen.Return
,所以你的try..except会抓到这个异常并报错,所以改下BaseHandler.args_kwargs
的代码,可参照:BTW.貌似
args_kwargs
里没有yield,貌似只是拿个参数而已,没必要用gen.coroutine
right?