我开始使用龙卷风和电机的一个小项目,如果我想要一个非bloking访问,我感到有些困惑,如何我必须处理访问数据层
通常我将我的项目与这个结构分开
root_project -logic -data --UsersDao -handlers --Users -main.py但我不知道我是否做了这样的事情,连接将是非阻塞的
@gen.coroutine @tornado.web.asynchronous def get(self, id): users = self.settings["User"] result = yield from users.get(id) self.write(json_encode(result)) self.finish()'users'是我的UsersDao对象,看起来像
class UsersDao(object): .... def get(self, user, callback=None): try: user = yield self._db["users"].find_one({'_id': user}) ...create user object return user except ValueError: pass except OperationFailure: pass except Exception: raiseI started a little project using tornado and motor, I feel some confused respect how i have to handle the access data layer if i want to have a non-bloking access
usally i separate my project with this structure
root_project -logic -data --UsersDao -handlers --Users -main.pybut i don't know if i do something like this the connection would be non-blocking
@gen.coroutine @tornado.web.asynchronous def get(self, id): users = self.settings["User"] result = yield from users.get(id) self.write(json_encode(result)) self.finish()'users' it's my UsersDao object and looks like
class UsersDao(object): .... def get(self, user, callback=None): try: user = yield self._db["users"].find_one({'_id': user}) ...create user object return user except ValueError: pass except OperationFailure: pass except Exception: raise最满意答案
通常,无论何时使用yield ,您都会执行异步/非阻塞操作。 所以在这种情况下,你发布的代码看起来是正确的,除了在@gen.coroutine上缺少@gen.coroutine装饰器(每当你使用yield for asynchronous stuff时,你需要这个装饰器,你需要在你调用它时使用yield )。
In general, whenever you use yield, you're doing something asynchronous/non-blocking. So in this case the code you've posted looks correct except for the missing @gen.coroutine decorator on UsersDao.get (whenever you use yield for asynchronous stuff, you need this decorator, and you need to use yield any time you call it).
更多推荐
发布评论