为了实现异步的DB访问,我尝试在我的旋风式应用程序中切换MongoEngine和MotorEngine,但到目前为止,我还没有得到任何进展。
query
@gen.coroutine
def get_all_users(self):
users = yield User.objects.find_all()handler
class IUser(BaseHandler):
@asynchronous
@gen.engine
def get(self,userId=None, *args, **kwargs):
try:
userMethods = UserMethods()
sessionId = self.request.headers.get('sessionId')
ret = userMethods.get_all_users()
except Exception as ex:
print str(ex)
self.finish()当我打印ret变量时,它是<tornado.concurrent.Future object at 0x7fb0236fe450>。如果我试图打印ret.result(),它将使我一事无成。
任何帮助都是值得感激的,因为我一直在为我想的一切而挣扎.
发布于 2014-09-23 12:54:51
get_all_users需要以某种方式返回它的值。在Python2.6或2.7中,生成器不允许使用“返回”语句,因此coroutines有一个特殊的“返回”异常:
@gen.coroutine
def get_all_users(self):
users = yield User.objects.find_all()
raise gen.Return(users)在Python3.3和更高版本中,您可以简单地“返回用户”。
现在,在"get“中,调用"get_all_users”只会给出一个未决的未来,而不是一个值。您必须等待未来通过产生一个值来解决它:
ret = yield userMethods.get_all_users()有关从coroutines调用coroutines的更多信息,请参见我的“重构龙卷风协同”。
顺便说一句,你可以用"gen.coroutine“来装饰"get”,它比“异步”和"gen.engine“更现代,但这两种风格都很管用。
发布于 2016-05-10 13:13:01
只是个建议。如果您想避免每次使用userMethods方法时都要创建它的实例:
userMethods = UserMethods()您可以在声明@classmethod装饰符之前使用它:
class UserMethods():
pass
@classmethod
@tornado.gen.coroutine
def get_all_users(self):
users = yield User.objects.find_all()
raise gen.Return(users)
## class IUser
...
try:
# userMethods = UserMethods() --not necesary now--
sessionId = self.request.headers.get('sessionId')
ret = yield userMethods.get_all_users()
except Exception as ex:
print str(ex)
...https://stackoverflow.com/questions/25993260
复制相似问题