python - how to yield gen.coroutine methods -
i'm running tornado server following class:
class sessionhandler(tornado.websocket.websockethandler): def open(self): pass def on_close(self): pass @tornado.gen.coroutine def on_message(self,message): #db added tornado application object on init self.application.db.add("test") x=self.application.db.get("test") print(x)
the function follows (part of db class):
@tornado.gen.coroutine def get(self,key): result=[] lookup=yield self.postcol.find_one({"_id":key}) if not lookup: return result id in lookup["fieldarray"]: ob=yield self.postcol.find_one({"_id":objectid(id)}) result.append(ob) return result
i won't type add() function out. realised get() returns future object instead of array. that's fine, realise need change code x=yield self.application.db.get("test"). question add() function has no explicit return value in method. still need yield when call i.e. yield self.application.db.add("test")?
it work without yielding i'm wondering if it's mistake not yield because know return future object.
if that's case mean have yield method call decorated gen.coroutine?
yes, should "yield" call coroutine. there 2 reasons:
- if don't yield, coroutine spawned , runs concurrently calling coroutine. want wait "add" finish before executing next statement in "on_message"? way make "on_message" wait "add" complete yield future returned "add".
- if "add" throws exception--for example if network connection database fails, or if document invalid or violates unique index--the way know exception thrown yield future returned "add". otherwise exception silently ignored, see the big warning in tornado's coroutine documentation.
Comments
Post a Comment