検索

ホームページ  >  に質問  >  本文

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中文网2888日前332

全員に返信(2)返信します

  • 伊谢尔伦

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

    元の try 以外を削除してください。try 以外はレイズをキャッチします。次のように変更してください。問題ありません。

    リーリー

    返事
    0
  • 阿神

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

    Python2.x では、ジェネレーターは直接 return 值 できないため、Tornado は値を特別な例外にラップして返します。この例外は gen.Return であるため、try..Except はこの例外をキャッチし、エラーが発生します。報告されているので、BaseHandler.args_kwargs のコードを変更します。
    には、yield はないようです。args_kwargs を使用する必要はありません。 > そうですよね? gen.coroutine リーリー

    返事
    0
  • キャンセル返事