search

Home  >  Q&A  >  body text

python - tonado raise gen.Return 错误

最近在使用 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

不能返回数据,请问有大神知道原因吗?请指教,非常感谢!

PHP中文网PHP中文网2887 days ago330

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:32:03

    Original, remove the try except, try except will catch the raise, change it to the following, it should be OK

    class BaseHandler(tornado.web.RequestHandler):
        @gen.coroutine
        def args_kwargs(self,pro):
            kwargs = self.get_argument("data", None)
            if kwargs:
                code = "-10000"
                raise gen.Return(code)
            else:
                raise gen.Return("xxx")
            
    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:
                err = traceback.format_exc()
                self.write(err)
                self.finish() 
               

    reply
    0
  • 阿神

    阿神2017-04-17 17:32:03

    In Python2.x, the generator cannot be directly return 值,所以Tornado把值包在一个特殊的异常里返回出来,这个异常就是gen.Return,所以你的try..except会抓到这个异常并报错,所以改下BaseHandler.args_kwargs的代码,可参照:
    BTW.貌似args_kwargs里没有yield,貌似只是拿个参数而已,没必要用gen.coroutine right?

    class BaseHandler(tornado.web.RequestHandler):
        @gen.coroutine
        def args_kwargs(self,pro):
            try:
                kwargs = self.get_argument("data",None)
            except Exception as e:
                print e
            else:
                code = "-10000" if kwargs else "0000000"
                raise gen.Return(code)
    
    
    class EventAPIHandler(BaseHandler):
        @gen.coroutine
        def post(self):
            try:
                code = yield self.args_kwargs("event")
                if code:
                    self.write(re_code[code])
                    self.finish()    # gen.coroutine会自动finish(),如果只是想结束连接,可把这一行替换为 return
            except Exception,e:
                print traceback.format_exc()

    reply
    0
  • Cancelreply